【问题标题】:Trying to access boolean variable from all instances of a class尝试从类的所有实例访问布尔变量
【发布时间】:2020-09-08 13:20:56
【问题描述】:

我正在尝试在 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'

【问题讨论】:

    标签: python multithreading tkinter checkbox


    【解决方案1】:

    您必须存储创建的实例。我能想到的有两种可能: 全局变量 (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)
    

    【讨论】:

    • 第一个解决方案无法获得正确的checkbutton值,第二个解决方案甚至会引发NameError
    • 应该是self.instances.append(self)
    【解决方案2】:

    您正在调用该类,但您应该调用该类的实例。

    我觉得应该是这样的:

    instance = checkbutton_gen()
    for checkbox in instance.checkbuttonvalue:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-11
      • 2010-10-23
      • 2012-08-20
      • 1970-01-01
      • 2011-05-11
      • 2014-08-30
      相关资源
      最近更新 更多