问题描述
我试图在Tkinter中打印复选框的布尔值,我创建了一个最小的复制示例,类似于我的原始代码。
看起来好像不需要线程,但是对于我的实际项目来说是必需的。
无论如何,我只是尝试访问类checkbutton_gen
的每个实例的复选框变量
这是代码:
import threading
from tkinter import *
root = Tk()
class checkbutton_gen(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.checkbuttonvalue = BooleanVar(value=False)
def run(self):
self.checkbutton = Checkbutton(root,onvalue=True,offvalue=False,textvariable=self.checkbuttonvalue)
self.checkbutton.pack()
for count in range(10):
thread = checkbutton_gen()
thread.start()
Button(root,text='Check to see of checkboxes are ticked',command=lambda:check()).pack()
def check():
for checkbox in checkbutton_gen.checkbuttonvalue:
print(checkbutton_gen.checkbuttonvalue)
root.mainloop()
这是我遇到的错误:
for checkbox in checkbutton_gen.checkbuttonvalue:
AttributeError: type object 'checkbutton_gen' has no attribute 'checkbuttonvalue'
解决方法
您将必须存储创建的实例。我可以想到两种可能性: 全局变量(considered bad)
checkboxes = []
for count in range(10):
thread = checkbutton_gen()
checkboxes.append(thread)
def check():
for checkbox in checkboxes:
print(checkbox.checkbuttonvalue)
静态变量
class checkbutton_gen(threading.Thread):
instances = []
def __init__(self):
self.instances.append(self) # or checkbutton_gen.instances.append(self)
...
def check():
for checkbox in checkbutton_gen.instances:
print(checkbox.checkbuttonvalue)
,
您正在调用该类,但是您应该调用该类的实例。
我认为应该是这样的:
instance = checkbutton_gen()
for checkbox in instance.checkbuttonvalue: