Python tkinter checkbutton值无法访问

时间:2016-03-03 11:06:31

标签: python checkbox tkinter

我想在Python中构建一个小的GUI应用程序。目标是让一个主窗口调用其他几个窗口。在其中一个被称为窗口的我有一个检查按钮。我的问题是我无法读取此checkbutton的值,而我可以读取Entry小部件的值。我做错了什么?

    from tkinter import *
    import tkinter as tk


    class mainwindow():
        def __init__(self, master):

            self.master = master
            menubalk = Menu(self.master)

            menubalk.add_command(label="New window", command=self.openNewwindow)
            self.master.config(menu=menubalk)

        def openNewwindow(self):
            window = newwindow()
            window.mainloop()

    class newwindow(Tk):

        def __init__(self):
            Tk.__init__(self)

            self.var = BooleanVar()
            self.checkbutton = Checkbutton(self, text="Check", variable=self.var)
            self.checkbutton.grid(column=0, row=0)

            self.var2 = StringVar()
            self.entry = Entry(self, textvariable=self.var2)
            self.entry.grid(column=2,row=0)

            self.button2 = Button(self,text=u"Show", command=self.showValues).grid(column=1, row=0)

        def showValues(self):
            print('Value checkbutton:', self.var.get(), ';', 'Value entryfield: ', self.entry.get())

    def main():
        root = Tk()
        window = mainwindow(root)
        root.mainloop()

    if __name__ == '__main__':
        main()

2 个答案:

答案 0 :(得分:2)

您正在程序中制作多个独立的Tkinter应用程序。不要那样做。要创建新窗口,请使用Toplevel小部件。

from tkinter import *

class mainwindow():
    def __init__(self, master):

        self.master = master
        menubalk = Menu(self.master)

        menubalk.add_command(label="New window", command=self.openNewwindow)
        self.master.config(menu=menubalk)

    def openNewwindow(self):

        def showValues(var, entry):
            print('Value checkbutton:', var.get(), ';', 'Value entryfield: ', entry.get())

        window = Toplevel(self.master)
        var = BooleanVar()
        checkbutton = Checkbutton(window, text="Check", variable=var)
        checkbutton.grid(column=0, row=0)

        var2 = StringVar()
        entry = Entry(window, textvariable=var2)
        entry.grid(column=2,row=0)

        button2 = Button(window,text=u"Show", command=lambda: showValues(var, entry))
        button2.grid(column=1, row=0)

def main():
    root = Tk()
    window = mainwindow(root)
    root.mainloop()

if __name__ == '__main__':
    main()

答案 1 :(得分:-1)

Tkinter的变量对象(IntVar,StringVar等)必须接受参数" master"作为他们的第一个参数。即替换

self.var=StringVar()

使用

self.var=StringVar(self)

self.var=StringVar(master=self)