First Python Tkinter window works, but the rest are blank
I think I'm missing something basic about Tkinter.
What would be th开发者_C百科e correct way to create several windows with the same hidden root window? I can get one window to open, but once it's closed subsequent ones show up blank, without any widgets in them. I've also noticed if I leave the root window visible, it disappears when I close the first "real" window.
I would post code, but I haven't been able to figure out what causes the behavior, and my actual code is fairly complicated, and has to run inside another (even more complicated) program.
I've tried using .quit()
or .destroy()
to close windows, and put mainloop()
s and wait_window()
loops in different places, but everything either still has the error or something worse goes wrong. I guess what I'm looking for is just a different perspective.
My problem seems similar to the one here, but I haven't been able to gain anything new from the answer.
Any ideas? I know this is a little vague. Thanks
SOLVED:
This probably won't help anyone, but I figured out the problem. I have several classes of windows, each derived from Tkinter.Toplevel. In my base Window
class I made a close()
function that calls self.destroy()
. Then in its subclasses I added custom code to store their geometry etc, and finally called Window.close(self)
. Something about that doesn't work, because if I just use self.quit()
instead of invoking the superclass's close()
, everything is fine.
Your question is too vague to know for certain what the problem is. Rest assured, when you use it right it's quite easy to create multiple windows, and to hide and show them at will.
You ask what the correct way to create multiple windows is; the answer to that is to call Toplevel() for each window, nothing more, nothing less. It is then up to you to place widgets inside of that window. There's no secret, no hidden options, no extra commands. Just make sure that the parent for each child widget is set appropriately.
Here's a simple example:
import Tkinter as tk
import sys
def exit():
sys.exit(0)
root = tk.Tk()
root.wm_withdraw()
for i in range (10):
top = tk.Toplevel(root)
top.title("Window %s" % i)
label = tk.Label(top, text="This is toplevel #%s" % i)
button = tk.Button(top, text="exit", command=exit)
label.pack()
button.pack()
root.mainloop()
精彩评论