Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter messagebox not behaving like a modal dialog

I am using messagebox for a simple yes/no question but that question should not be avoided so I want to make it unavoidable and it seems if I have one question box.

messagebox.askyesno("text", "question?")

Then I can go back to the root window of tkinter with the question still waitng for response, but if I have

messagebox.askyesno("text", "question?")
messagebox.askyesno("text", "question?")

With the first messagebox open I can still go back to the root window of tkinter but with the other questionbox I am unable to ( like I need). This applies to every messagebox I tested. Can anybody explain me why that is and how can I make the first question box unavoidable or I just have to do a blank messagebox before my actual question box. Is there anything I am doing wrong, because I think message box should not care if there has been a message box before it.

To illustrate my point better, I started to put together a simple nicely organised example, and it worked perfectly. I figured out what were the differences, as I started to use messagebox for the first time, I wanted to test its capabilities, and did not put it in a function. In a function it works perfectly.

like image 677
user1362446 Avatar asked Oct 12 '12 18:10

user1362446


1 Answers

Use grab_setto keep the focus off root until the messagebox has been answered. Alternatively call wait_window() after opening the messagebox. Only need 1 or the other

import tkinter as tk
from tkinter.messagebox import askyesno

def onClick():
    root.grab_set() # Prevent clicking root while messagebox is open
    ans = askyesno('Confirm', 'Press Yes / No')
    root.wait_window() # Prevent clicking root while messagebox is open
    if ans:
        print('Yes Pressed')
    else:
        print('No Pressed')

root = tk.Tk()

tk.Button(root, text='Click me', command=onClick).pack()

root.mainloop()
like image 167
Steven Summers Avatar answered Sep 30 '22 19:09

Steven Summers