Search code examples
pythontkintermainloop

Presenting tk instances with Tk.mainloop()


I am programming a yahtzee simulator (for learning) and would like to have a few screens (tkinter instances) running at the same time but i dont want them to start at the same time and I can't figure out why they do start in the same time.

I haven't tried much except googling about it, I am new to tkinter programming...

from tkinter import *
Screen1 = Tk()
screen2 = Tk()

Screen1.mainloop()

I excpected that only screen1 would be shown but they both are being shown, any help?


Solution

  • You are explicitly creating two windows, so two windows appear.

    You should never create more than one instance of Tk. If you need multiple windows, the second and subsequent windows need to be instances of Toplevel. You only need to call mainloop once -- it's not what creates the windows, it's simply the mechanism by which windows can respond to events. One call to mainloop is all you need no matter how many windows you have.

    The reason for this is based on how tkinter is implemented -- tkinter is a thin wrapper around an embedded tcl interpreter (a completely different programming language environment), and each instance gets its own interpreter. That means that all of the widgets and tkinter variables (StringVar, etc) in one instance are invisible and inaccessible to any other instance.

    If you want to create additional windows but have them hidden initially, you can call the withdraw method on any window you want to hide.