tkinter 复选按钮未设置变量 [英] tkinter checkbutton not setting variable
本文介绍了tkinter 复选按钮未设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无论我对我的复选按钮做什么,它似乎都没有设置变量.以下是所涉及的代码部分:
Whatever I do to my checkbutton, it does not seem to set the variable. Here's the parts of the code that are involved:
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.我做错了什么吗?没有其他任何东西可以手动操作.
It just keeps printing 0. Am I doing something wrong? Nothing else does anything to manual.
推荐答案
您正在寻找 IntVar()
IntVar()
有一个名为 get()
的方法,它将保存您分配给它的小部件的值.
IntVar()
has a method called get()
which will hold the value of the widget you assign it to.
在此特定实例中,它将是 1 或 0(开或关).你可以像这样使用它:
In this particular instance, it will be either 1 or 0 (On or off). You can use it something like this:
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()
这篇关于tkinter 复选按钮未设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文