【问题标题】:How to get the tick boxes to change value in the second window?如何让复选框在第二个窗口中更改值?
【发布时间】:2016-12-02 10:29:21
【问题描述】:

我得到的示例代码有两个窗口,第二个窗口中有一个勾选框,它在勾选时不会改变值。我怎样才能解决这个问题?我尝试返回复选框的值,但也失败了。

from tkinter import *

root = Tk()

def open_custom_gui():
    custom_gui()

b = Button(root,command=open_custom_gui)
b.grid(row=1,column=0)

def custom_gui():
    def getinfo():
        print(var1.get())

    custom= Tk()
    var1 = IntVar()
    tickbox_1 = Checkbutton(custom,text='TEST',variable=var1,)
    tickbox_1.grid(row=0,column=0)
    b = Button(custom,command=getinfo)
    b.grid(row=1,column=0)

    custom.mainloop()

root.mainloop()

【问题讨论】:

    标签: python python-3.x user-interface checkbox tkinter


    【解决方案1】:

    问题与两次调用Tk() 有关。您可以通过显式创建第二个Toplevel 窗口来解决此问题。

    from tkinter import *
    
    root = Tk()
    
    def open_custom_gui():
        custom_gui()
    
    b = Button(root, command=open_custom_gui)
    b.grid(row=1, column=0)
    
    def custom_gui():
        def getinfo():
            print(var1.get())
    
        custom = Toplevel()  # CHANGE THIS (don't call Tk() again)
        var1 = IntVar()
        tickbox_1 = Checkbutton(custom, text='TEST', variable=var1)
        tickbox_1.grid(row=0, column=0)
        b = Button(custom, command=getinfo)
        b.grid(row=1, column=0)
    
        custom.mainloop()
    
    root.mainloop()
    

    或者,您也可以通过在创建 IntVar tkinter 变量时指定第二个 Tk 实例来修复它:

    def custom_gui():
        def getinfo():
            print(var1.get())
    
        custom = Tk()
        var1 = IntVar(master=custom)  # ADD a "master" keyword argument
        tickbox_1 = Checkbutton(custom, text='TEST', variable=var1)
        tickbox_1.grid(row=0, column=0)
        b = Button(custom, command=getinfo)
        b.grid(row=1, column=0)
    
        custom.mainloop()
    

    但是我建议使用第一种方法,因为 documentation 表示以下内容(关于将参数添加到 IntVar 构造函数):

    只有当你运行 Tkinter 时,构造函数参数才相关 多个 Tk 实例(你不应该这样做,除非你真的知道什么 你在做)。

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2023-01-10
    • 1970-01-01
    • 2016-04-07
    相关资源
    最近更新 更多