如何设置ttk.Combobox的背景颜色

时间:2015-01-12 23:01:57

标签: python-3.x combobox tkinter background-color ttk

我在使用tkinter ttk和' vista'设置Combobox的背景颜色时遇到问题。主题(我使用Python 3)。我从这里尝试过代码ttk.Combobox glitch when state is read-only and out of focus

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
combo = ttk.Combobox(root, values=['1', '2', '3'])
combo['state'] = 'readonly'
combo.pack()
tk.Entry(root).pack()

style = ttk.Style()
style.map('TCombobox', selectbackground=[('readonly', 'red')])
#style.map('TCombobox', fieldbackground=[('readonly', 'blue')]) #not working as well

但这只会改变文本的背景,组合框的其余部分会保持白色。另外,我在tcl论坛上看到了一个帖子:http://wiki.tcl.tk/15780我已尝试使用' fieldbackground'但似乎tkinter忽略了这个参数。你知道怎么解决吗?也许有一种方法只能在特定主题中配置特定样式?我看到了默认'主题,如果状态为“只读”,则背景会变为灰色。

3 个答案:

答案 0 :(得分:3)

显然,您设置新样式属性的顺序对于确定是否应用新样式的某个属性非常重要。例如,如果我先设置background而不是selectbackground,则不会更改选择的颜色,而只会更改带箭头的迷你按钮颜色(列出选项)。

我还注意到,根据parent的值,我认为是父样式,从中派生出新的样式,其中一些可能不会应用新样式的新设置和属性。例如,如果我在fieldbackground设置为parent时尝试更改aqua属性,则它不起作用,但如果parent设置为alt , 有用。 (我希望更多专家用户可以提供帮助,并为改进此答案做出贡献,这对ttktkinter 的未来用户也有帮助。

这是我的解决方案,我在其中创建了一个全新的风格:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

combostyle = ttk.Style()

combostyle.theme_create('combostyle', parent='alt',
                         settings = {'TCombobox':
                                     {'configure':
                                      {'selectbackground': 'blue',
                                       'fieldbackground': 'red',
                                       'background': 'green'
                                       }}}
                         )
# ATTENTION: this applies the new style 'combostyle' to all ttk.Combobox
combostyle.theme_use('combostyle') 

# show the current styles
# print(combostyle.theme_names())

combo = ttk.Combobox(root, values=['1', '2', '3'])
combo['state'] = 'readonly'
combo.pack()

entry = tk.Entry(root)
entry.pack()

root.mainloop()

由于我不是ttk的专家,因此我无法将新的主题仅应用于ttk.Combobox类型的某个实例,但我应用了< em> theme 到未来可能ttk.Combobox的所有实例。如果有人能改进这个答案,我真的很感激这个姿态!

有关如何创建和设置新样式的详细信息,请参阅herehere

答案 1 :(得分:3)

以下代码对我来说很好。重要的是设置参数的顺序。

`

    style = ttk.Style()

    style.map('TCombobox', fieldbackground=[('readonly','white')])
    style.map('TCombobox', selectbackground=[('readonly', 'white')])
    style.map('TCombobox', selectforeground=[('readonly', 'black')])

    self.mycombo = ttk.Combobox(self.frame,textvariable=self.combo_var,
                                height=15,justify='left',width=21,
                                values=lista)

    self.mycombo['state'] = 'readonly' # Set the state according to configure colors
    self.mycombo.bind('<<ComboboxSelected>>',
                      lambda event: self._click_combo())

`

答案 2 :(得分:0)

如果您只想更改颜色而不考虑小部件的状态(即悬停、按下等...),那么您将需要使用 configure 方法而不是 {{ 1}} 方法,因为 map 方法专门用于将各种格式应用于特定的小部件状态。由于您只使用“只读”状态,我认为这就是您想要的。

map
相关问题