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

使用CustomTkinter创建新窗口时,顶层窗口无法置顶的问题

解决CustomTkinter中CTkToplevel窗口无法置于顶层的问题

CTkToplevel默认不会强制保持在顶层,你可以通过设置窗口属性来解决这个问题——在创建窗口后添加attributes('-topmost', True),就能让窗口始终处于所有窗口之上。如果后续需要允许其他窗口覆盖它,也可以将该属性设为False。

修改后的代码如下:

from customtkinter import CTk, CTkToplevel, CTkLabel, CTkButton

class Gui:
    def __init__(self):
        self.root = CTk()
        self.root.geometry('600x600')
        self.new_window_button = CTkButton(master=self.root, text="Open new window", 
                                           width=120, height=36, command=self.new_window)
        self.new_window_button.pack()

        self.root.mainloop()

    def new_window(self):
        new_window = CTkToplevel(self.root)
        # 设置窗口始终置顶
        new_window.attributes('-topmost', True)
        # 可选:让窗口立即获得焦点
        new_window.focus()
        CTkLabel(master=new_window, text="This is a new CustomTk window").pack()

if __name__ == '__main__':
    Gui()

如果你只需要临时将窗口提到顶层,也可以用new_window.lift()方法,但这个方法不会让窗口一直保持置顶状态,当其他窗口被激活时可能会被覆盖,而-topmost属性能持续维持窗口的顶层优先级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:22:33