0

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 . How can i achieve it ?

Below is the code i used but it resp value is always 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()
  • Related: https://stackoverflow.com/a/51651826/3714930 – fhdrsdg Aug 07 '18 at 08:11
  • Here i want to close only MessageBox .Root shouldn't be destroyed . Is there anyway to destroy only tkMessageBox?? – chandra kanth Chandra Aug 07 '18 at 11:30
  • I'm afraid that's not possible because you don't get a reference to the actual dialog window, you'd have to create your own [custom dialog window](http://effbot.org/tkinterbook/tkinter-dialog-windows.htm). – fhdrsdg Aug 07 '18 at 11:37

1 Answers1

2

With the default askyesno messagebox you cannot do this. 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()
fhdrsdg
  • 10,297
  • 2
  • 41
  • 62