首页 > 解决方案 > tkinter,Checkbutton,相同的代码在def或单个文件中具有不同的结果

问题描述

我有一个很奇怪的问题。

我为 Checkbutton (tkinter) 编写代码。

  1. 如果代码在一个文件中,它可以工作。“检查”按钮可以显示当前状态(数值变化)

调试——在检查过程中

C1 的值为:1

C2 的值为:0

调试——在检查过程中 C1 的值为:1

C2 的值为:1

2 如果代码在一个def中,值总是0(不改变)

我该如何解决这个问题?

谢谢

单个文件:

#!/usr/bin/python3

from tkinter import *


root = Tk()


CheckVar1 = IntVar()
CheckVar2 = IntVar()
Name1 =  "Music"
Name2 =  "Video"

C1 = Checkbutton(root, text = Name1, variable = CheckVar1, onvalue = 1,  offvalue = 0 )
C2 = Checkbutton(root, text = Name2, variable = CheckVar2,onvalue = 1, offvalue = 0 )

C1.pack()
C2.pack()

def check_value():
    print("Debug -- in check proc")
    print("The value of C1 is :", CheckVar1.get())
    print("The value of C2 is :", CheckVar2.get())


Button(root, text = 'check', command = check_value).pack()

mainloop()

带有def的文件

#!/usr/bin/python3

from tkinter import *

def tree_ts_summary():
    root = Tk()
    
    
    CheckVar1 = IntVar()
    CheckVar2 = IntVar()
    Name1 =  "Music"
    Name2 =  "Video"
    
    C1 = Checkbutton(root, text = Name1, variable = CheckVar1, onvalue = 1,  offvalue = 0 )
    C2 = Checkbutton(root, text = Name2, variable = CheckVar2,onvalue = 1, offvalue = 0 )
    
    C1.pack()
    C2.pack()
    
    def check_value():
        print("Debug -- in check proc")
        print("The value of C1 is :", CheckVar1.get())
        print("The value of C2 is :", CheckVar2.get())
    
    
    Button(root, text = 'check', command = check_value).pack()
    
    mainloop()


root_top = Tk()

Button(root_top, text = 'call_def', command = tree_ts_summary).pack()

mainloop()


标签: pythontkinter

解决方案


正如@acw1668 在评论中提到的,您不应该有多个 Tk() 实例。您可以像这样更改代码:

from tkinter import *

def tree_ts_summary():

    
    
    CheckVar1 = IntVar()
    CheckVar2 = IntVar()
    Name1 =  "Music"
    Name2 =  "Video"
    
    C1 = Checkbutton(root, text = Name1, variable = CheckVar1, onvalue = 1,  offvalue = 0 )
    C2 = Checkbutton(root, text = Name2, variable = CheckVar2,onvalue = 1, offvalue = 0 )
    
    C1.pack()
    C2.pack()
    
    def check_value():
        print("Debug -- in check proc")
        print("The value of C1 is :", CheckVar1.get())
        print("The value of C2 is :", CheckVar2.get())
    
    
    Button(root, text = 'check', command = check_value).pack()
    


root = Tk()

Button(root, text = 'call_def', command = tree_ts_summary).pack()
root.mainloop()

推荐阅读