Python Tkinter - destroy window after time or on click

非 Y 不嫁゛ 提交于 2020-01-06 05:28:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!