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

如何在Tkinter中移除已创建的菜单栏?

如何移除Tkinter中已创建的菜单栏

移除整个菜单栏

你只需要调用窗口的config()方法,将menu参数设为空字符串或者None,就能完全移除当前显示的菜单栏——毕竟当初就是通过root.config(menu=menubar)把菜单栏绑定到窗口上的,反向操作即可。

示例代码(在你提供的创建代码基础上添加移除按钮):

from tkinter import * 
from tkinter.ttk import * 
from time import strftime
  
# 创建tkinter窗口
root = Tk()
root.title('Menu Demonstration')
  
# 创建菜单栏
menubar = Menu(root)
  
# 添加File菜单及命令
file = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='File', menu = file)
file.add_command(label ='New File', command = None)
file.add_command(label ='Open...', command = None)
file.add_command(label ='Save', command = None)
file.add_separator()
file.add_command(label ='Exit', command = root.destroy)
  
# 添加Edit菜单及命令
edit = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Edit', menu = edit)
edit.add_command(label ='Cut', command = None)
edit.add_command(label ='Copy', command = None)
edit.add_command(label ='Paste', command = None)
edit.add_command(label ='Select All', command = None)
edit.add_separator()
edit.add_command(label ='Find...', command = None)
edit.add_command(label ='Find again', command = None)
  
# 添加Help菜单
help_ = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Help', menu = help_)
help_.add_command(label ='Tk Help', command = None)
help_.add_command(label ='Demo', command = None)
help_.add_separator()
help_.add_command(label ='About Tk', command = None)
  
# 显示菜单栏
root.config(menu = menubar)

# 定义移除菜单栏的函数
def remove_menu():
    root.config(menu='')  # 也可以用 root.config(menu=None)

# 添加触发移除的按钮
Button(root, text="移除菜单栏", command=remove_menu).pack(pady=20)

mainloop()

移除单个菜单项(比如某一个菜单标签)

如果不需要移除整个菜单栏,只想删掉其中一个菜单(比如File),可以调用菜单栏对象的delete()方法,传入菜单的索引或者标签名:

  • 通过索引删除:menubar.delete(0)(0是第一个菜单的索引,对应创建顺序里的File)
  • 通过标签删除:menubar.delete('File')

示例代码(添加删除单个菜单的按钮):

# ... 原菜单栏创建代码保持不变 ...

# 定义删除File菜单的函数
def delete_file_menu():
    menubar.delete('File')  # 或者用 menubar.delete(0)

# 添加触发删除的按钮
Button(root, text="删除File菜单", command=delete_file_menu).pack(pady=20)

root.config(menu = menubar)
mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:35:16