Tkinter消息框的行为不像模式对话框 [英] Tkinter messagebox not behaving like a modal dialog

查看:134
本文介绍了Tkinter消息框的行为不像模式对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用消息框来回答一个简单的是/否问题,但不应避免该问题,因此我想避免它的出现,好像我有一个问题框.

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?")

然后我可以回到tkinter的根窗口,问题仍然在等待响应,但是如果我有

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?")

在第一个消息框打开的情况下,我仍然可以返回到tkinter的根窗口,但是在其他问题框下,我无法打开(就像我需要的那样).这适用于我测试过的每个消息框.谁能解释我为什么这样,以及如何使第一个问题框不可避免,或者我只需要在我的实际问题框前做一个空白messagebox即可.我做错了什么吗,因为我认为消息框应该不在乎之前是否有消息框.

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.

为了更好地说明我的观点,我开始整理一个简单而井井有条的示例,并且效果很好.我弄清楚有什么区别,当我第一次开始使用messagebox时,我想测试其功能,而没有将其放入函数中.在功能上,它运行完美.

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.

推荐答案

使用grab_set可以使焦点始终保持root状态,直到回答了消息框为止.或者,在打开消息框后调用wait_window().只需要一个或另一个

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

这篇关于Tkinter消息框的行为不像模式对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆