Python Tkinter-时间或单击后销毁窗口 [英] Python Tkinter - destroy window after time or on click
本文介绍了Python Tkinter-时间或单击后销毁窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
import tkinter as tk
from tkinter import messagebox
try:
w = tk.Tk()
w.after(3000, lambda: w.destroy()) # Destroy the widget after 3 seconds
w.withdraw()
messagebox.showinfo('MONEY', 'MORE MONEY')
if messagebox.OK:
w.destroy()
w.mainloop()
confirmation = 'Messagebox showed'
print(confirmation)
except Exception:
confirmation = 'Messagebox showed'
print(confirmation)
是否有更好的方法可以执行此操作而不使用线程和捕获异常?
Is there better way to do this, without using threading and catching exception?
推荐答案
您使用if messagebox.OK:
,但是messagebox.OK
被定义为OK = "ok"
.因此,您的if语句始终为true.如果要检查用户是否单击了按钮,则需要获取showinfo
函数的返回值.
You use if messagebox.OK:
, but messagebox.OK
is defined as OK = "ok"
. Therefore, your if statement is always true. If you want to check whether the user clicked the button you need to get the return value of the showinfo
function.
因此您可以这样做:
a = messagebox.showinfo('MONEY', 'MORE MONEY')
if a:
w.destroy()
或更短:
if messagebox.showinfo('MONEY', 'MORE MONEY'):
w.destroy()
当用户未单击任何内容时(因此w.destroy
调用已运行w.destroy
时),不会运行w.destroy
.
This way w.destroy
is not run when the user didn't click anything (so when w.destroy
has already been run by the after
call).
总计:
import tkinter as tk
from tkinter import messagebox
w = tk.Tk()
w.withdraw()
w.after(3000, w.destroy) # Destroy the widget after 3 seconds
if messagebox.showinfo('MONEY', 'MORE MONEY'):
w.destroy()
confirmation = 'Messagebox showed'
print(confirmation)
这篇关于Python Tkinter-时间或单击后销毁窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文