【问题标题】:Tkinter: How to default-check the checkbuttons generated by for loopsTkinter:如何默认检查 for 循环生成的复选按钮
【发布时间】:2023-01-15 10:05:47
【问题描述】:

我尝试将每个项目的默认值设置为列表的布尔值,但仍未选中。

我有下面的代码片段。它是使用 forloop 创建的,用于生成多个复选按钮。在我试图实现的程序中,有更多这样的复选按钮。但我已将它们减少到以下五个。

from tkinter import *

class App():
    def __init__(self, root):
        keys = [True, True, False, False, False]
        self.root = root
        for n in range(0, 5):
            self.CheckVar = BooleanVar()
            self.checkbutton = Checkbutton(self.root, text = 'test_' + str(n), variable = self.CheckVar.set(keys[n])).pack()
           
root = Tk()
app = App(root)
root.mainloop()

或者我也试过这种方式。

        for n in range(0, 5):
            self.CheckVar = BooleanVar(value=keys[n])
            self.checkbutton = Checkbutton(self.root, text = 'test_' + str(n), variable = self.CheckVar).pack()

然后这些复选按钮使用户能够修改列表的布尔值。

【问题讨论】:

    标签: python for-loop tkinter checkbox


    【解决方案1】:

    使用 select() 方法,您可以 check 盒子。

    将您的 for 循环从:

    for n in range(0, 5):
        self.CheckVar = BooleanVar()
        self.checkbutton = Checkbutton(self.root, text = 'test_' + str(n), variable = self.CheckVar.set(keys[n])).pack()
    

    到:

    for n in range(0, 5):
        self.CheckVar = BooleanVar()
        self.checkbutton = Checkbutton(self.root, text = 'test_' + str(n), variable = self.CheckVar.set(keys[n]))
        self.checkbutton.select()
        self.checkbutton.pack()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 2022-08-19
      • 2021-01-02
      • 2012-04-22
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 2021-11-10
      相关资源
      最近更新 更多