Reputation: 1446
I got the following code from a tutorial. I then modified main()
so that two windows are created as seperate threads. When I run it, only one window is created. Then when I press the Quit
button in that window, a second window appears. In this new window the button has a different look than the first one (a look which I like better) and then if I press either of the two Quit
buttons, both windows close and the program exits.
Why does the second window not appear until the first Quit
button is pressed, and why does it look different when it does appear?
EDIT: This happens when no threads are used as well, where only one window is created at a time.
EDIT: This is a screenshot of the two windows that are created. The one on the left is created with the program is run, the one on the right is created after clicking the "Quit" button on the first.
from Tkinter import Tk, BOTH
from ttk import Frame, Button, Style
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Quit button")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
quitButton = Button(self, text="Quit",
command=self.quit)
quitButton.place(x=50, y=50)
from threading import Thread
def main():
for i in range(2):
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
Thread(target=root.mainloop()).start()
if __name__ == '__main__':
main()
Upvotes: 0
Views: 1847
Reputation: 385980
You cannot use tkinter this way. Tkinter isn't thread safe, you can only ever access tk widgets and commands except from the thread that created the root window.
As for one window only showing after the other is destroyed even without threading, it's hard to say since you don't show the code. If you're creating more than one instance of Tk
, and calling mainloop
more than once, that's the problem. Tkinter is designed to work when you create precisely one instance of Tk
, and call mainloop
precisely once.
If you want more than one window, create a single instance of Tk
for the first window, and instances of Toplevel
for additional windows.
Upvotes: 1