【问题标题】:tkinter checkbutton not setting variabletkinter checkbutton未设置变量
【发布时间】:2017-11-08 11:32:44
【问题描述】:

无论我对我的检查按钮做什么,它似乎都没有设置变量。 以下是涉及的代码部分:

class Window:
    def __init__(self):
        self.manualb = 0 #to set the default value to 0

    def setscreen(self):
        #screen and other buttons and stuff set here but thats all working fine
        manual = tkr.Checkbutton(master=self.root, variable=self.manualb, command=self.setMan, onvalue=0, offvalue=1) #tried with and without onvalue/offvalue, made no difference
        manual.grid(row=1, column=6)

    def setMan(self):
        print(self.manualb)
        #does some other unrelated stuff

它只是一直打印 0。我做错了什么吗?没有其他任何东西可以手动操作。

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    您正在寻找IntVar()

    IntVar() 有一个名为 get() 的方法,它将保存您分配给它的小部件的值。

    在这个特定的例子中,它将是 1 或 0(开或关)。 你可以像这样使用它:

    from tkinter import Button, Entry, Tk, Checkbutton, IntVar
    
    class GUI:
    
        def __init__(self):
    
            self.root = Tk()
    
            # The variable that will hold the value of the checkbox's state
            self.value = IntVar()
    
            self.checkbutton = Checkbutton(self.root, variable=self.value, command=self.onClicked)
            self.checkbutton.pack()
    
        def onClicked(self):
            # calling IntVar.get() returns the state
            # of the widget it is associated with 
            print(self.value.get())
    
    app = GUI()
    app.root.mainloop()
    

    【讨论】:

    • 嗨@Jebby。解释为什么某人应该或不应该在他们的程序中做/使用某事通常是一个好主意。这使刚接触您所描述的想法和语言的人更容易理解答案。
    • 感谢@EthanField 我已经编辑了我的帖子以包含更多关于IntVar 是什么的信息。
    【解决方案2】:

    这是因为您需要使用 tkinter 的variable classes 之一。

    这看起来像下面这样:

    from tkinter import *
    
    root = Tk()
    
    var = IntVar()
    
    var.trace("w", lambda name, index, mode: print(var.get()))
    
    Checkbutton(root, variable=var).pack()
    
    root.mainloop()
    

    本质上IntVar() 是一个“容器”非常松散地说),它“持有”它分配给的小部件的值.

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 2020-12-05
      • 1970-01-01
      • 2019-10-14
      • 2020-05-04
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      相关资源
      最近更新 更多