简体   繁体   English

Python 2.7 Tkinter-多个窗口条目更新

[英]Python 2.7 Tkinter - Multiple window entry update

I would like the text to appear and be updated in each window, instead of only in one. 我希望文本在每个窗口中显示和更新,而不是仅在一个窗口中显示和更新。 I have noticed that the window that works is always the first that is being called, but that does not help me solve the issue. 我注意到,可以正常工作的窗口始终是第一个被调用的窗口,但这无助于我解决问题。

Another thing I noticed is that the program accepts entering new values into the windows that display a value in the first place, but any attempt to change de value by entering a value in the second window fails. 我注意到的另一件事是,该程序接受在首先显示值的窗口中输入新值,但是通过在第二个窗口中输入值来更改de值的任何尝试均会失败。

Here is a simplified version of my code: 这是我的代码的简化版本:

from Tkinter import *

root = Tk()
root2 = Tk()
de= IntVar()
de.set(0)

def previous():
    de.set(de.get()-1)

def Next():
    de.set(de.get()+1)

def go_to(event) :
    de.set(de.get())

button4 =Button( root2, text='Next', command=Next )
button4.grid(row=26 ,column=9, columnspan=2, rowspan=1,padx=0, pady=0, sticky=W+E+N+S)
button5 =Button( root2, text='Previous', command=previous )
button5.grid(row=26, column=6, columnspan=2, rowspan=1,padx=0, pady=0, sticky=W+E+N+S)

label1=Label(root2, text = 'Go to2')
entry1 = Entry(root2,textvariable=de,bd=1,width=3)
entry1.bind("<Return>", go_to)
label1.grid(row=25, column=8, columnspan=1, rowspan=1,padx=0, pady=0)
entry1.grid(row=26, column=8, columnspan=1, rowspan=1,padx=0, pady=0)

button3 =Button( root, text='Next', command=Next )
button3.grid(row=26 ,column=9, columnspan=2, rowspan=1,padx=0, pady=0, sticky=W+E+N+S)
button2 =Button( root, text='Previous', command=previous )
button2.grid(row=26, column=6, columnspan=2, rowspan=1,padx=0, pady=0, sticky=W+E+N+S)

label=Label(root, text = 'Go to1')
entry = Entry(root,textvariable=de,bd=1,width=3)
entry.bind("<Return>", go_to)
label.grid(row=25, column=8, columnspan=1, rowspan=1,padx=0, pady=0)
entry.grid(row=26, column=8, columnspan=1, rowspan=1,padx=0, pady=0)

root2.mainloop()
root.mainloop()

The root cause of the problem is that Tkinter isn't designed to have two root windows. 问题的根本原因是Tkinter的设计没有两个根窗口。 Doing so has some unexpected side effects such as what you're seeing. 这样做会产生一些意想不到的副作用,例如您所看到的。 In effect, you can think of the two root windows as two separate processes or threads which cannot share information. 实际上,您可以将两个根窗口视为两个无法共享信息的单独的进程或线程。 Your IntVar belongs to the first window, but you're trying to use it in the second. 您的IntVar属于第一个窗口,但是您试图在第二个窗口中使用它。

The fix is to never create more than one instance of Tk . 解决方法是永远不要创建多个Tk实例。 If you need more windows, create instances of Toplevel . 如果需要更多窗口,请创建Toplevel实例。 Doing that, you can share the same IntVar among as many windows as you want. 这样,您就可以在所需的多个窗口之间共享同一个IntVar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM