如何在python中创建一个保存checkbutton状态的按钮?

2024-06-26 08:23:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python3中使用tkinter。 我的GUI上有一个checkbutton和button:

entercheck = Checkbutton(window1, variable = value)
entercheck.pack()
savebutton = Button(window1, width=5, height=2, command = savecheck)
savebutton.pack()

其中value=IntVar()。 我试图使其在单击时,将checkbutton的状态保存到变量status。我试过:

^{pr2}$

但是,无论checkbutton是否被选中,这总是导致status(它是一个全局变量)等于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()

Tags: textselfmastervaluetkinterdefbuttonvariable
2条回答

statussavecheck函数的局部变量。使它成为一个全球性的,它将按预期工作。在

status = 0
value = IntVar()

def savecheck():
    global status
    status = value.get()

entercheck = Checkbutton(self, variable = value)
entercheck.pack()
savebutton = Button(self, width=5, height=2, command = savecheck)
savebutton.pack()

老实说,我不太清楚为什么你的程序不起作用,但是我有一个解决方案。在

pressbttn1()函数中,更改:

    window1 = Tk()

^{pr2}$

调用Tk()创建一个新的根窗口。调用Toplevel()创建一个独立的顶层窗口widget,该窗口独立于根窗口存在,但由同一个窗口管理器控制。一个应用程序可以有任意数量的。在

有关窗口管理器的其他信息,请参见Toplevel Window Methods。在

相关问题 更多 >