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

如何在Python GUI中创建可自定义尺寸与颜色的菜单栏

用Tkinter实现自定义样式菜单栏

Tkinter的原生菜单栏依赖系统自带组件,受系统主题限制,无法直接修改颜色、高度这类样式。但可以通过Frame和Button组件手动模拟菜单栏,实现完全自定义的外观:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("自定义菜单栏")
root.geometry("600x400")

# 自定义菜单栏容器,设置红色背景与固定高度
menu_frame = tk.Frame(root, bg="#ff0000", height=50)
menu_frame.pack(fill="x")
menu_frame.pack_propagate(False)  # 阻止容器随子组件自动调整尺寸

# 配置菜单按钮样式
style = ttk.Style()
style.configure("Menu.TButton",
                foreground="white",
                background="#ff0000",
                font=("Arial", 12),
                padding=10)

# 文件菜单按钮与下拉菜单
def show_file_menu():
    file_menu.post(file_btn.winfo_rootx(), file_btn.winfo_rooty() + file_btn.winfo_height())

file_btn = ttk.Button(menu_frame, text="文件", style="Menu.TButton", command=show_file_menu)
file_btn.pack(side="left")

file_menu = tk.Menu(root, tearoff=0)
file_menu.add_command(label="新建")
file_menu.add_command(label="打开")
file_menu.add_separator()
file_menu.add_command(label="退出", command=root.quit)

# 编辑菜单按钮与下拉菜单
def show_edit_menu():
    edit_menu.post(edit_btn.winfo_rootx(), edit_btn.winfo_rooty() + edit_btn.winfo_height())

edit_btn = ttk.Button(menu_frame, text="编辑", style="Menu.TButton", command=show_edit_menu)
edit_btn.pack(side="left")

edit_menu = tk.Menu(root, tearoff=0)
edit_menu.add_command(label="复制")
edit_menu.add_command(label="粘贴")

root.mainloop()

这段代码通过红色背景的Frame作为菜单栏容器,固定高度为50,按钮样式与背景统一,点击按钮可弹出标准下拉菜单,完全满足自定义尺寸与颜色的需求。

推荐的其他GUI模块
  • PyQt/PySide:功能全面的跨平台GUI框架,支持通过QSS(Qt样式表)直接自定义菜单栏的颜色、尺寸等样式,文档完善,社区资源丰富,适合构建复杂专业的界面。
  • CustomTkinter:基于Tkinter的现代化增强库,自带支持自定义样式的菜单栏组件,无需手动模拟,直接通过参数设置颜色、高度,上手简单,适合快速搭建美观的桌面应用。
  • Kivy:专注跨平台的NUI(自然用户界面)框架,支持通过KV语言或代码完全自定义菜单栏样式,适配移动端与桌面端,适合开发交互性强的应用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:54:58