python tk窗口 选择 销毁_Python Tkinter-时间或点击后销毁窗口

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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值