python - tkinter,Checkbutton,相同的代码在def或单个文件中具有不同的结果
问题描述
我有一个很奇怪的问题。
我为 Checkbutton (tkinter) 编写代码。
- 如果代码在一个文件中,它可以工作。“检查”按钮可以显示当前状态(数值变化)
调试——在检查过程中
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()
解决方案
正如@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()
推荐阅读
- spring-boot - 带 Spring 的 ZeroMQ (spring-integration-zeromq)
- python - 使用正则表达式根据单引号拆分熊猫行中的列表
- jquery - jQuery:删除一个特定的点击处理程序保留其他人
- matlab - 如何为某些点绘制具有不同颜色的网格(MATLAB)
- javascript - 无法读取未定义的 react-native-image-picker 的属性“launchImageLibrary”
- android - 解码位图返回 null
- symfony - 在 Entity SYMFONY 中使用构造函数进行计算
- google-apps-script - 将发票发送到电子邮件条纹(Google App Scir
- javascript - getUserMedia 的奇怪行为
- r - 用许多变量(大约 70 个)在 R 中进行逻辑回归