如何移除ttk.Menubutton的箭头(附额外问题)
一、彻底移除箭头
直接修改样式布局,移除箭头元素,无需处理hover等状态下的颜色匹配:
修改Styles.style_menubar方法,重定义Menubutton的布局结构,仅保留标签部分:
@staticmethod def style_menubar(style: ttk.Style): background_color = "#130E0B" style.configure("Menubar.TFrame", background=background_color) # 重写布局,去掉箭头组件 style.layout("Menu.TMenubutton", [ ("Menubutton.border", {"sticky": "nswe", "children": [ ("Menubutton.padding", {"sticky": "nswe", "children": [ ("Menubutton.label", {"sticky": "nswe"}) ]}) ]}) ]) style.configure("Menu.TMenubutton", background=background_color, foreground="#EDEDED", activebackground="#5C5C5C", relief='flat', padding=(0, 0))
二、缩小Menubutton宽度
移除箭头后,通过以下操作消除文本与原箭头位置的间隙:
- 在样式配置中设置
padding=(0,0),清除组件内边距 - 创建Menubutton时,设置
pack(padx=0)消除外部边距
完整修改后的代码示例
Styles类
class Styles: @staticmethod def apply_theme(): style = ttk.Style() style.theme_use('clam') @staticmethod def style_menubar(style: ttk.Style): background_color = "#130E0B" style.configure("Menubar.TFrame", background=background_color) # 重写布局移除箭头 style.layout("Menu.TMenubutton", [ ("Menubutton.border", {"sticky": "nswe", "children": [ ("Menubutton.padding", {"sticky": "nswe", "children": [ ("Menubutton.label", {"sticky": "nswe"}) ]}) ]}) ]) style.configure("Menu.TMenubutton", background=background_color, foreground="#EDEDED", activebackground="#5C5C5C", relief='flat', padding=(0, 0))
Menubar类
class Menubar(ttk.Frame): def __init__(self, parent): super().__init__(parent) Styles.style_menubar(ttk.Style()) self.configure(style="Menubar.TFrame") self.create_menubar(parent) def create_menubar(self, root): file_menubutton = ttk.Menubutton(self, text="File", style="Menu.TMenubutton") file_menu = Menu(file_menubutton, tearoff=0) file_menu.add_command(label="New") file_menu.add_command(label="Open") file_menu.add_command(label="Save") file_menu.add_separator() file_menu.add_command(label="Exit", command=root.quit) file_menubutton["menu"] = file_menu # 清除外部边距 file_menubutton.pack(side=tk.LEFT, fill=tk.NONE, padx=0) # Additional buttons...
内容的提问来源于stack exchange,提问作者Solanaar
相关产品推荐
相关产品推荐

