为什么Toplevel显示2个窗口? [英] Why is Toplevel showing 2 windows?
问题描述
我正在尝试创建一个tkinter应用程序,该应用程序在第一个窗口(根)关闭时不会关闭所有内容(其他窗口).我试过使用Toplevel()
,它非常适合其他程序中的弹出窗口,但不能用于创建基本级别.
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()
我不知道这是否可行,或者我不知道是否可以更改Tk()
的属性以使其不关闭其他所有窗口.
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.
推荐答案
将显示两个窗口,因为创建tkinter小部件时,它也会强制创建Tk
实例以及每个小部件,除非parent是显式传递的,是自动创建的Tk
实例的子代.因此,您的代码本质上模仿了以下代码:
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()
现在有一些方法可以解决您想要的行为,一种方法是隐藏实际的Tk
实例:
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()
另一种方法是否决root
本身的删除,但是我怀疑这实际上是您想要的:
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()
这篇关于为什么Toplevel显示2个窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!