我想显示一个带有选项“是”或“否”的消息框。如果用户未在TIMEOUT(例如:5秒)内选择任何选项,则应使用默认的“是”选项关闭消息框。我该如何实现?
下面是我使用的代码,但是它的resp
值始终为False。
from Tkinter import *
import tkMessageBox
time = 2000
def status():
resp=True
root.destroy()
root = Tk()
root.withdraw()
root.after(time,status)
resp=tkMessageBox.askyesno(title='Test',message='Click Yes otherwise No',default=tkMessageBox.YES)
print resp
root.mainloop()
答案 0 :(得分:0)
使用默认的askyesno
消息框,您无法执行此操作。您可以使用自定义对话框来执行此操作,例如:
import Tkinter as tk
class MyDialog(tk.Toplevel):
def __init__(self, parent, text):
tk.Toplevel.__init__(self, parent)
tk.Label(self, text=text).grid(row=0, column=0, columnspan=2, padx=50, pady=10)
b_yes = tk.Button(self, text="Yes", command=self.yes, width=8)
b_yes.grid(row=1, column=0, padx=10, pady=10)
b_no = tk.Button(self, text="No", command=self.no, width=8)
b_no.grid(row=1, column=1, padx=10, pady=10)
self.answer = None
self.protocol("WM_DELETE_WINDOW", self.no)
def yes(self):
self.answer = "Yes"
self.destroy()
def no(self):
self.answer = "No"
self.destroy()
def popup():
d = MyDialog(root, "Click Yes or No")
root.after(5000, d.yes)
root.wait_window(d)
print d.answer
root = tk.Tk()
tk.Button(root, text="Show popup", command=popup).pack()
root.mainloop()