Python 尝试从类的所有实例访问布尔变量
我试图打印Tkinter中复选框的布尔值,我创建了一个最小的复制示例,它类似于我的原始代码 看起来似乎不需要线程,但我的实际项目需要线程 无论如何,我只是尝试访问类的每个实例的checkbox变量Python 尝试从类的所有实例访问布尔变量,python,multithreading,tkinter,checkbox,Python,Multithreading,Tkinter,Checkbox,我试图打印Tkinter中复选框的布尔值,我创建了一个最小的复制示例,它类似于我的原始代码 看起来似乎不需要线程,但我的实际项目需要线程 无论如何,我只是尝试访问类的每个实例的checkbox变量checkbutton\u gen 代码如下: import threading from tkinter import * root = Tk() class checkbutton_gen(threading.Thread): def __init__(self): th
checkbutton\u 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'
您必须存储创建的实例。我可以想到两种可能性: 全局变量() 静态变量
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)
您必须存储创建的实例。我可以想到两种可能性: 全局变量() 静态变量
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:
您正在调用该类,但应该调用该类的实例 我认为应该是这样的:
instance = checkbutton_gen()
for checkbox in instance.checkbuttonvalue:
第一个解决方案无法获得checkbutton的正确值,第二个解决方案甚至会引发
NameError
。它应该是self.instances.append(self)
。第一个解决方案无法获得checkbutton的正确值,第二个解决方案甚至会引发NameError
。它应该是self.instances.append(自)
。