尝试从一个类的所有实例访问布尔变量

问题描述

我试图在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:

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...