Tkinter messagebox not behaving like a modal dialo

2019-06-22 10:52发布

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.

1条回答
仙女界的扛把子
2楼-- · 2019-06-22 11:37

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()
查看更多
登录 后发表回答