安排窗口堆栈(.lift 方法)

将特定窗口提升到其他窗口之上的最基本情况,只需在该窗口上调用 .lift() 方法(ToplevelTk

import tkinter as tk #import Tkinter as tk #change to commented for python2

root = tk.Tk()

for i in range(4):
    #make a window with a label
    window = tk.Toplevel(root)
    label = tk.Label(window,text="window {}".format(i))
    label.pack()
    #add a button to root to lift that window
    button = tk.Button(root, text = "lift window {}".format(i), command=window.lift)
    button.grid(row=i)

root.mainloop()

但是,如果该窗口被破坏试图解除它将引发如下错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/.../tkinter/__init__.py", line 1549, in __call__
    return self.func(*args)
  File "/.../tkinter/__init__.py", line 785, in tkraise
    self.tk.call('raise', self._w, aboveThis)
_tkinter.TclError: bad window path name ".4385637096"

通常当我们尝试将特定窗口放在用户面前但关闭时,一个很好的选择是重新创建该窗口:

import tkinter as tk #import Tkinter as tk #change to commented for python2

dialog_window = None

def create_dialog():
    """creates the dialog window
  ** do not call if dialog_window is already open, this will
     create a duplicate without handling the other
if you are unsure if it already exists or not use show_dialog()"""
    global dialog_window
    dialog_window = tk.Toplevel(root)
    label1 = tk.Label(dialog_window,text="this is the dialog window")
    label1.pack()
    #put other widgets
    dialog_window.lift() #ensure it appears above all others, probably will do this anyway

def show_dialog():
    """lifts the dialog_window if it exists or creates a new one otherwise"""
    #this can be refactored to only have one call to create_dialog()
    #but sometimes extra code will be wanted the first time it is created
    if dialog_window is None:
        create_dialog()
        return
    try:
        dialog_window.lift()
    except tk.TclError:
        #window was closed, create a new one.
        create_dialog()
    
    
root = tk.Tk()

dialog_button = tk.Button(root,
                          text="show dialog_window",
                          command=show_dialog)
dialog_button.pack()
root.mainloop()

这样功能 show_dialog 将显示对话框窗口是否存在,同时请注意,在尝试抬起窗口而不是将其包裹在 try:except 中之前,你可以调用 .winfo_exists() 来检查它是否存在。

除了降低堆栈中的窗口外,还有 .lower() 方法与 .lift() 方法的工作方式相同:

import tkinter as tk #import Tkinter as tk #change to commented for python2

root = tk.Tk()
root.title("ROOT")
extra = tk.Toplevel()
label = tk.Label(extra, text="extra window")
label.pack()

lower_button = tk.Button(root,
                         text="lower this window",
                         command=root.lower)
lower_button.pack()

root.mainloop()

你会注意到它甚至低于其他应用程序也会降低,只能低于某个窗口,你可以将其传递给 .lower() 方法,类似地,也可以使用 .lift() 方法将窗口提升到另一个窗口之上。