安排視窗堆疊(.lift 方法)
將特定視窗提升到其他視窗之上的最基本情況,只需在該視窗上呼叫 .lift()
方法(Toplevel
或 Tk
)
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()
方法將視窗提升到另一個視窗之上。