Tkinter messagebox not behaving like a modal dialog

一世执手 提交于 2019-12-10 14:26:00

问题


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:


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


来源:https://stackoverflow.com/questions/12865392/tkinter-messagebox-not-behaving-like-a-modal-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!