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

如何正确实现Tkinter的lift方法?使NEW_FRAME置于根窗口Frame上层

解决Tkinter中Frame无法通过lift()正确置顶的问题

我看了你的代码,问题其实出在两个小细节上:一是lift()的调用不够明确,二是每次点击按钮都会重复创建新Frame,导致界面叠加混乱。咱们一步步来修复:

1. 明确指定lift的目标组件

你当前用的new.lift()确实能尝试提升Frame,但如果要确保它稳稳覆盖在welcome Frame之上,最好明确指定要置于哪个组件的上方——也就是用new.lift(welcome)。这样Tkinter就清晰知道要把新Frame放在原有Frame的上层了。

2. 避免重复创建Frame

每次点击"NEWS"按钮,你的代码都会生成一个新的红色Frame,多次点击后会有多个Frame叠在一起,不仅占资源,还可能让布局变得奇怪。咱们可以把new变量设为全局的,每次创建前先销毁旧的Frame,保证界面始终只有一个新Frame。

修改后的完整代码

from tkinter import *

root = Tk()
root.geometry("1300x600")

# 原有欢迎Frame
welcome = Frame(root, bg="yellow")
welcome.pack(fill=BOTH, expand=True)
label = Label(welcome, text="welcome bro to page one")
label.grid(row=45, column=50)
b = Label(welcome, text="you can select menu bar to switch page")
b.grid(row=100, column=500)

# 全局变量存储新Frame,方便复用/销毁
new_frame = None

def NEWS_Frame():
    global new_frame
    # 如果之前已经创建过新Frame,先销毁它
    if new_frame is not None:
        new_frame.destroy()
    # 创建新Frame
    new_frame = Frame(root, bg="red")
    new_frame.pack(fill=BOTH, expand=True)
    l1 = Label(new_frame, text="Have been waiting for")
    l1.grid(row=49, column=80)
    l2 = Label(new_frame, text="hello dude how be things")
    l2.grid(row=0, column=0)
    # 明确将新Frame提升到welcome的上方
    new_frame.lift(welcome)

# 菜单栏
MAIN_MENU = Menu(root)
root.config(menu=MAIN_MENU)
File_menu = Menu(MAIN_MENU)
MAIN_MENU.add_cascade(label="NEW PAGE", menu=File_menu, underline=0)
File_menu.add_command(label="NEWS", command=NEWS_Frame)

root.mainloop()

额外小建议

你在Label里用了超大的row和column值(比如row=45、column=500),这会强行拉宽拉高原Frame的尺寸,其实没必要。如果只是想让Label居中,你可以给grid设置权重或者用pack(anchor=CENTER),这样布局会更合理简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:49:03