简体   繁体   English

tKmessagebox超时后自动选择

[英]tKmessagebox automatic selection after a timeout

I want to display a messagebox with options Yes or No. If user doesn't select any option with in the TIMEOUT(ex:5 sec) Messagebox should be closed with default YES option . 我想显示一个带有选项“是”或“否”的消息框。如果用户未在TIMEOUT(例如:5秒)中选择任何选项,则应使用默认的“是”选项关闭消息框。 How can i achieve it ? 我该如何实现?

Below is the code i used but it resp value is always False. 以下是我使用的代码,但其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()

With the default askyesno messagebox you cannot do this. 使用默认的askyesno消息框,您无法执行此操作。 You can do this with a custom dialog like for example: 您可以使用自定义对话框来执行此操作,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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