简体   繁体   English

Python Tkinter-时间或点击后销毁窗口

[英]Python Tkinter - destroy window after time or on click

I have following code: 我有以下代码:

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? 有没有不使用线程和捕获异常的更好的方法来做到这一点?

You use if messagebox.OK: , but messagebox.OK is defined as OK = "ok" . 您可以使用if messagebox.OK:messagebox.OK被定义为OK = "ok" Therefore, your if statement is always true. 因此,您的if语句始终为true。 If you want to check whether the user clicked the button you need to get the return value of the showinfo function. 如果要检查用户是否单击了按钮,则需要获取showinfo函数的返回值。

So you can do: 因此,您可以执行以下操作:

a = messagebox.showinfo('MONEY', 'MORE MONEY')
if a:
    w.destroy()

Or even shorter: 甚至更短:

if messagebox.showinfo('MONEY', 'MORE MONEY'):
    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). 当用户未单击任何内容时, w.destroy不会运行(因此, w.destroy已经由after调用运行)。

In total: 总共:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM