由于某种原因,使用按钮关闭tkinter弹出窗口需要您更新窗口以将其关闭(否则它将坐在那里,但是调用update来关闭窗口会引发异常。
我尝试了以下方法,该方法可以工作,但会引发一个异常,我无法在最终产品中使用它:
Button1 = ttk.Button(popupWindow, text="Close", command=popupWindow.destroy)
Button1.pack(expand = Y)
while popupWindow:
time.sleep(0.1)
popupWindow.update()
我也尝试过显而易见的try / except方法:
Button1 = ttk.Button(popupWindow, text="Close", command=popupWindow.destroy)
Button1.pack(expand = Y)
while popupWindow:
time.sleep(0.1)
try:
popupWindow.update()
except:
pass
这只会导致程序挂起并变得无响应,就好像它在等待popupWindow.update()的调用一样。有没有一种方法可以使所引发的异常静音?
您不应该使用while循环,sleep
和update
来等待按钮单击或等待窗口消失。这些是您所看到的异常的根本原因。
Tkinter具有专门用于此目的的功能。使用这些功能之一,您将不必尝试捕获异常,因为不会引发异常。
在您的情况下,您似乎想等待小部件被销毁。您可以使用tkinter的“ wait_window”函数来完成此操作-等待窗口被销毁。
这是一个人为制作的弹出窗口示例。创建它时,它将新窗口置于其父窗口的中心,然后等待直到该窗口被销毁。本示例使用Frame
作为基础,但是您也可以使用Toplevel
或Canvas
或任何其他小部件。
import tkinter as tk
class PopupWindow(tk.Frame):
def __init__(self, parent, message):
tk.Frame.__init__(
self, parent,
borderwidth=2, relief="raised",
background="bisque",
)
label = tk.Label(self, text=message, bg=self.cget("background"))
ok_button = tk.Button(self, text="Ok", command=self.destroy)
ok_button.pack(side="bottom", pady=10)
label.pack(side="top", padx=20, pady=20)
# center this widget on parent window
self.place(relx=.5, rely=.5, anchor="center")
# wait until the window has been destroyed
self.wait_window(self)
这是使用此小部件的示例:
import tkinter as tk
class Example():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("400x400")
button = tk.Button(self.root, text="Do Something", command=self.do_something)
button.pack(side="top")
self.root.mainloop()
def do_something(self):
print("doing something...")
print("waiting...")
popupWindow = PopupWindow(self.root, "Click button to continue")
print("done waiting...")
ex = Example()
您可以使用以下方法忽略/沉默异常:
except:
pass
是否有使用time.sleep
的任何原因?
尽管可以通过创建顶层窗口top = Toplevel
使自己的弹出窗口足够容易。您可以使用root.withdraw
将主屏幕隐藏为一个选项,如果希望将其扩展为完整的弹出屏幕,请设置top.attribute(-zoomed, True)
。
[当您想破坏Toplevel
屏幕时,请像使用弹出窗口一样使用command=top.destroy
,然后使用root.iconify
再次图标化根窗口