2016-12-01 65 views
0

我得到的代码示例有两个窗口,第二个窗口中有一个勾选框,它在勾选时不会更改值。我怎样才能解决这个问题?我试着返回tickbox的值,但是失败了。如何获取勾选框来更改第二个窗口中的值?

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() 

回答

2

问题有事情做与调用Tk()两次。您可以通过明确创建第二个窗口来修复该问题。

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() 

另外,您还可以通过指定第二Tk例如,当您创建IntVar Tkinter的变量解决这个问题:

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的构造函数中):

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

+1

非常感谢! –

相关问题