You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter:实现类似VC++ DoModal()对话框并让子窗口始终置顶

解决Tkinter子对话框被父窗口覆盖的问题

嘿,我太懂你这个困扰了——Tkinter的Toplevel窗口默认确实不会自动钉在父窗口上方,点一下父窗口就被盖过去,这体验确实有点糟。不过只需要加一行代码就能完美解决!

核心解决方案:绑定子窗口到父窗口

用transient()方法把你的子对话框和父窗口绑定起来,这样它会始终依附在父窗口的顶层,还会跟着父窗口一起最小化、关闭,完全符合你想要的dlg.DoModal()那种模态对话框的感觉。

修改后的完整代码

我在你的代码里加了关键的一行,特意标出来了:

# python 2.7
import Tkinter as tk
import tkFont
from Tkinter import IntVar
from Tkinter import *

class MyGUI():
    def __init__(self, master):
        self.master = master
        ## Set the focus on dialog window (needed on Windows)
        master.focus_set()
        ## Make sure events only go to our dialog
        master.grab_set()

def start_test():
    handle = tk.Toplevel(root)
    # 关键代码:将子窗口设为父窗口的临时从属窗口,始终保持顶层
    handle.transient(root)
    my_login_dialog = MyGUI(handle)
    handle.wait_window(handle)

root = tk.Tk()
root.title('')
root.geometry('1024x768')
ft1 = tkFont.Font(size = 10,weight = 'bold')
tk.Button(root,text = 'Button_A',bg = 'white',height = 1,width = 8,font = ft1, command = start_test).place(x = 50,y = 10)
root.mainloop()

另一种极端方案:强制全局置顶

如果你希望子窗口不仅在父窗口上方,甚至能压过所有其他软件的窗口,可以用这个方法:

handle.attributes('-topmost', True)

不过这种方式会让窗口一直浮在最前面,哪怕你切到其他软件也不会消失,适合特殊场景,一般用transient就足够满足需求啦。

修改后你再点击父窗口,子对话框就再也不会被覆盖了,完全达到你想要的效果~

内容的提问来源于stack exchange,提问作者Billy Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:17:58