ttk.ComboBox 样式未正确设置

3 投票
2 回答
2620 浏览
提问于 2025-04-18 15:40

我创建了一个Python的图形界面应用程序,运行得很好,我把所有的东西都调整得很满意,除了那个下拉框(ComboBox)。我发现对ttk.Combobox的样式设置似乎不起作用。

这应该能给你一个我想要的材料风格的感觉。下面是我为下拉框设置的样式代码。

globalStyle = ttk.Style()
globalStyle.configure('TCombobox', foreground=textColor, background=backgroundColor, fieldbackground=selectColor, fieldforeground=textColor, font='Verdana')

我唯一能成功改变的就是文字和前景色。我想修改以下几个属性:

文字颜色
输入框背景
下拉框文字颜色
下拉框背景

补充说明:我用的颜色变量都是有效的十六进制颜色代码。

selectColor = '#333333'
backgroundColor = '#444444'
foregroundColor = '#555555'
textColor = '#999999'

2 个回答

-1

我知道这个问题已经有半年了,但我遇到过类似的问题,并且成功解决了。要改变ttk下拉框的颜色,你可以使用以下代码:

# these imports are indeed only valid for python 3.x
import tkinter as tk
import tkinter.ttk as ttk

# for python 2.x the following import statements should work:
# import Tkinter as tk
# import ttk

root = tk.Tk()

# adding the options to the root elements
# (all comboboxes will receive this options)
root.option_add("*background", "#444444"),
root.option_add("*foreground", "#999999"),

# create a combobox
ttk.Combobox(root, values=["Banana", "Coconut", "Strawberry"]).pack()

root.mainloop()

我不太确定自己是否完全理解tk的样式机制。不过,以上代码在Python 3.2和Python 3.4上对我来说是有效的。

0

我遇到了同样的问题,不过我找到了解决办法,具体可以参考这里。你只需要在你的代码中添加以下内容:

option add *TCombobox*Listbox.background color 
option add *TCombobox*Listbox.font font 
option add *TCombobox*Listbox.foreground color 
option add *TCombobox*Listbox.selectBackground color 
option add *TCombobox*Listbox.selectForeground color

然后,如果你想在下拉框不显示的时候改变框内的字体,可以在代码中加上 font='font_style'

在我的例子中,我用了:

class CreateProfile(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg='dodgerblue4')
        label = tk.Label(self, text="Create Profile", font=large_font, bg='dodgerblue4', fg='deepskyblue')
        label.grid(columnspan=10, row=0, column=0, pady=5, padx=5)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)

        self.option_add("*TCombobox*Listbox*Background", "dodgerblue")
        self.option_add("*TCombobox*Listbox*Font", "pirulen")

        self.list_c = ttk.Combobox(self, values=("1", "2", "3", "4"), font='pirulen')
        self.list_c.grid(row=1, column=1, pady=5, padx=5)

确保你还要添加以下的导入:

import tkinter as tk
import tkinter.ttk as ttk

我现在的问题是,我只能改变实际框的背景颜色(下拉框不显示的时候)。我还在想怎么改变字体颜色(前景色对我没用),以及框本身的颜色。所以如果有人能补充一下这个答案,那就太好了!

撰写回答