先吐槽一下,csdn里面一堆机器人写的文章,连评论都是一样的=。=
先说问题出现的原因,如果使用Tkinter库创建超过1个窗口,就会出现IntVar()、StringVar()绑定组件无效的情况,无论怎么get都是同一个值
问题复现,示例代码:
import tkinter as tk
import time
def p():
print("windows1:"+str(radio.get()))
def p1():
print("windows2:"+str(radio1.get()))
root = tk.Tk()
radio = tk.IntVar()
root.minsize(200, 100)
root.maxsize(200, 100)
R1 = tk.Radiobutton(root, text="1", variable=radio, value=1 ,command=p)
R1.place(x=10,y=10)
R2 = tk.Radiobutton(root, text="2", variable=radio, value=2 ,command=p)
R2.place(x=80,y=10)
root1 = tk.Tk()
radio1 = tk.IntVar()
root1.minsize(200, 100)
root1.maxsize(200, 100)
R11 = tk.Radiobutton(root1, text="1", variable=radio1, value=1 ,command=p1)
R11.place(x=10,y=10)
R21 = tk.Radiobutton(root1, text="2", variable=radio1, value=2 ,command=p1)
R21.place(x=80,y=10)
root.mainloop()
root1.mainloop()
窗口1的IntVar是绑定成功的,但是窗口2的IntVar绑定失败,一直都是0
重点来了,在网上大部分文章初始化IntVar的时候都是这样的(被坑死):
radio = tk.IntVar()
我们去看一下IntVar()的源代码
class IntVar(Variable):
"""Value holder for integer variables."""
_default = 0
def __init__(self, master=None, value=None, name=None):
"""Construct an integer variable.
MASTER can be given as master widget.
VALUE is an optional value (defaults to 0)
NAME is an optional Tcl name (defaults to PY_VARnum).
If NAME matches an existing variable and VALUE is omitted
then the existing value is retained.
"""
Variable.__init__(self, master, value, name)
init方法里有一个master的参数,我们修改一下代码,把master参数补上
radio1 = tk.IntVar(master=root1)
那么完整代码是如下:
import tkinter as tk
import time
def p():
print("windows1:"+str(radio.get()))
def p1():
print("windows2:"+str(radio1.get()))
root = tk.Tk()
radio = tk.IntVar()
root.minsize(200, 100)
root.maxsize(200, 100)
R1 = tk.Radiobutton(root, text="1", variable=radio, value=1 ,command=p)
R1.place(x=10,y=10)
R2 = tk.Radiobutton(root, text="2", variable=radio, value=2 ,command=p)
R2.place(x=80,y=10)
root1 = tk.Tk()
radio1 = tk.IntVar(master=root1)
root1.minsize(200, 100)
root1.maxsize(200, 100)
R11 = tk.Radiobutton(root1, text="1", variable=radio1, value=1 ,command=p1)
R11.place(x=10,y=10)
R21 = tk.Radiobutton(root1, text="2", variable=radio1, value=2 ,command=p1)
R21.place(x=80,y=10)
root.mainloop()
root1.mainloop()
运行结果如下:
两个窗口都正常了
结论:使用Tkinter创建多个窗口的情况下,除第一个窗口以外,其余窗口的IntVar和StringVar变量在初始化时要指定master参数,master就是组件所在的窗口
完结撒花!