【发布时间】:2015-04-06 23:11:13
【问题描述】:
我在 python 3 中使用 tkinter。 我的 GUI 上有一个复选按钮和按钮:
entercheck = Checkbutton(window1, variable = value)
entercheck.pack()
savebutton = Button(window1, width=5, height=2, command = savecheck)
savebutton.pack()
在哪里value=IntVar()。
我试图做到这一点,以便在单击时按钮将检查按钮的状态保存到变量status。我试过了:
def savecheck():
global status
status = value.get()
但是,无论检查按钮是否被选中,这总是导致状态(它是一个全局变量)等于 0。这是为什么呢?
我看过这个问题:Getting Tkinter Check Box State,这个方法似乎对他们有用?
编辑:
我创建了一个较小版本的程序来尝试让它工作,这次只是尝试输出 checkbutton 变量的值,但它仍然不起作用。这是整个代码:
from tkinter import *
root=Tk()
def pressbttn1():
def savecheck():
print (value.get()) #outputs 0 no matter whether checked or not???
window1 = Tk()
value=IntVar()
entercheck = Checkbutton(window1, bg="white", variable = value)
entercheck.pack()
savebttn = Button(window1,text= "Save", command = savecheck)
savebttn.pack()
class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.create_widgits()
def create_widgits(self):
self.bttn1 = Button(self, text= "New Window", command = pressbttn1)
self.bttn1.pack()
#main
app=Application(root)
root.mainloop()
我不明白为什么上面的代码不起作用,当下面的代码起作用时:
from tkinter import *
master = Tk()
def var_states():
print(check.get())
check = IntVar()
Checkbutton(master, text="competition", variable=check).pack()
Button(master, text='Show', command=var_states).pack()
mainloop()
【问题讨论】:
-
我无法使用
root而不是self重现您的问题,因为root = Tkinter.Tk()- 所以您的问题可能是因为entercheck和savebutton是局部变量。尝试将它们设为全局变量或将它们存储为self的属性:即self.entercheck = Checkbutton(...)和self.savebutton = Button(...)。 -
糟糕,对不起,我在这里输入错误 self - 在我的程序中它是 window1,因为有多个窗口。
-
哦,不,这个错误是否与它位于与主窗口不同的窗口有关?
-
我建议尝试为问题创建一个简短的自包含说明 (SSCCE)——它甚至可以帮助您自己解决问题。我提到将小部件保存为全局变量或属性,因为在处理 Tkinter 时不做其中一个通常是一个问题。局部变量在它们所在的函数或方法返回后不再存在,如果您被告知 Tkinter 使用它们,可能会导致问题。
-
@martineau 请看我的编辑。
标签: python button python-3.x checkbox tkinter