Tkinter Notebook中ttk组件自定义样式未生效问题
问题分析
你创建了自定义ttk主题"yummy",但仅对TNotebook和TNotebook.Tab做了样式配置,没有为TCombobox和TButton定义自定义样式规则,因此这两个组件会沿用父主题"alt"的默认样式,导致显示效果不符合预期。
解决方案
在自定义主题的settings字典中,添加TCombobox和TButton的样式配置,将它们的外观规则纳入自定义主题体系。
以下是修改后的完整代码:
from tkinter import * from tkinter import ttk from tkinter.messagebox import askyesno root = Tk() root.geometry("500x500+10+10") main_frame = Frame(root) main_frame.configure(width=2000, height=1400) main_frame.pack(expand=True, fill=BOTH) login_frame1 = Frame(main_frame) login_frame1.configure(width=2000, height=1400) login_frame1.pack(expand=True, fill=BOTH) COLOR_GREEN = "#996666" COLOR_select = "#b3cccc" frame_color = 'white' input_color = '#c7d1d1' label_font = ('calibri',12, 'bold') input_font = ('times',12) # 自定义主题:添加TCombobox和TButton的样式配置 style = ttk.Style() style.theme_create("yummy", parent="alt", settings={ "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } }, "TNotebook.Tab": { "configure": {"padding": [5, 1], "background": COLOR_GREEN, "font" : ('times', '11', 'bold')}, "map": {"background": [("selected", COLOR_select)], "expand": [("selected", [1, 1, 1, 0])] } }, # 配置TButton样式 "TButton": { "configure": {"background": COLOR_GREEN, "foreground": "white", "font": input_font, "padding": [5, 2]}, "map": {"background": [("active", COLOR_select)], "foreground": [("active", "black")]} }, # 配置TCombobox样式 "TCombobox": { "configure": {"fieldbackground": input_color, "background": COLOR_GREEN, "font": input_font, "foreground": "black"}, "map": {"fieldbackground": [("readonly", input_color)], "background": [("active", COLOR_select)]} } }) style.configure("yummy", focuscolor=style.configure(".")["background"]) style.theme_use("yummy") # 创建Notebook及标签页 notebook = ttk.Notebook(login_frame1) notebook.pack(expand=True, fill=BOTH) tab1 = Frame(notebook, bg=frame_color) tab2 = Frame(notebook, bg=frame_color) tab1.pack(expand=True, fill= BOTH) notebook.add(tab1, text='Table 1') notebook.add(tab2, text='Table 2') notebook.select(tab1) # 界面元素 txt = 'Table View' lbl = Label(tab1, text=txt, font=('Gloss And Bloom',20,'bold'), fg='red', bg='white') lbl.place(x=80, y=5, relwidth=1, height=45) combo = ttk.Combobox(tab1, values=["选项1", "选项2", "选项3"]) # 添加示例选项 combo.place(x=10, y=60) # 调整位置避免被标题覆盖 btn = ttk.Button(tab1, text='Click me', width=20) btn.place(x=10, y=100) root.mainloop()
关键修改点说明
- 在
theme_create的settings中新增了TButton和TCombobox的样式规则,包括默认状态的configure和交互状态的map映射。 - 调整了组件的位置,避免标题标签覆盖下拉框和按钮。
- 给Combobox添加了示例选项,方便直观查看效果。
内容的提问来源于stack exchange,提问作者anikesh sharma
相关产品推荐
相关产品推荐

