简体   繁体   中英

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" . 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.

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).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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