Why is Toplevel showing 2 windows?

≯℡__Kan透↙ 提交于 2019-12-11 13:29:56

问题


I am trying to make a tkinter application which doesn't close everything (other windows) when the first window (root) is closed. I have tried to use Toplevel() which works perfectly for pop-up windows in other programs but not for making a base level.

from tkinter import *

top = Toplevel(bg='red')

top.mainloop()

I don't know if this is possible or I don't know if I can change the Tk()'s properties to make it so it doesn't shut all other windows down.


回答1:


There are two windows getting displayed because when a tkinter widget is created, it forces a Tk instance to be created as well, and every widget, unless a parent is explicitly passed, is a child to that automatically created Tk instance. So your code essentially mimics the following code:

from tkinter import *

root = Tk()

top = Toplevel(root, bg='red')

root.mainloop()

Now there are some ways to work around that for the behavior you want, one is to hide the actual Tk instance:

import tkinter as tk

root = tk.Tk()
root.withdraw()

top = tk.Toplevel(root, bg='red')

#to display root window again
#root.iconify()
#root.deiconify()
root.mainloop()

Another way would be to overrule the deletion of the root itself, but I doubt that's actually what you want:

import tkinter as tk


def callback():
    print("Won't close")

root = tk.Tk()

root.protocol("WM_DELETE_WINDOW", callback)

root.mainloop()


来源:https://stackoverflow.com/questions/48289171/why-is-toplevel-showing-2-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!