问题
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?
回答1:
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)
来源:https://stackoverflow.com/questions/51647603/python-tkinter-destroy-window-after-time-or-on-click