如何在 tkinter 中创建模式对话框?

2022-01-12 00:00:00 python python-3.x tkinter mfc

我有一个运行一些嵌入式 Python 脚本的 MFC 应用程序.我正在尝试制作这个嵌入式脚本创建的对话框之一,但我没有取得多大成功.

I have a MFC application which runs some embedded Python scripts. I am trying to make one of the dialogs this embedded script creates modal, but I am not having much success.

谁能告诉我制作模态对话框的方法?我需要为此使用 Windows 函数还是仅 Tk 或 Python 函数就足够了?

Can anyone point me the way to make a modal dialog? Do I need to use a windows functions for this or only Tk or Python functions are enough?

对于我在谷歌上搜索的内容,以下功能组合应该可以发挥作用,但它们似乎没有按我预期的方式工作:

For what I googled looks like the following combination of functions should do the magic, but they dont seem to work the way I was expecting:

focus_set()

grab_set()

transient(parent)

推荐答案

grab_set 是使窗口应用程序模式"的正确机制.也就是说,它从同一应用程序中的所有其他窗口(即:同一进程中的其他 Tkinter 窗口)获取所有输入,但它允许您与其他应用程序交互.

grab_set is the proper mechanism for making a window "application modal". That is, it takes all input from all other windows in the same application (ie: other Tkinter windows in the same process), but it allows you to interact with other applications.

如果您希望您的对话框是全局模式的,请使用 grab_set_global.这将接管整个系统的所有键盘和鼠标输入.使用此功能时您必须非常小心,因为如果您遇到阻止应用释放抓取的错误,您可以轻松地将自己锁定在计算机之外.

If you want your dialog to be globally modal, use grab_set_global. This will take over all keyboard and mouse input for the entire system. You must be extremely careful when using this because you can easily lock yourself out of your computer if you have have a bug that prevents your app from releasing the grab.

当我需要这样做时,在开发过程中我会尝试编写一个防弹的故障保护,例如一个计时器,它会在固定的时间后释放抓取.

When I have the need to do this, during development I'll try to write a bulletproof failsafe such as a timer that will release the grab after a fixed amount of time.

相关文章