How to set the background color of a ttk.Combobox

家住魔仙堡 提交于 2019-11-28 01:24:01

Apparently, the order you set the properties of the new style is important to determine if a certain property of the new style will be applied or not. For example, if I set first the background instead of selectbackground, then the color of selection will not be changed, but just the mini button color with the arrow (to list down the options).

I noted also that depending on the value of parent, which I suppose is the parent style from which the new style is derived, some of the new settings and properties of the new style might not be applied. For example, if I try to change the fieldbackground property when parent is set to aqua, it does not work, but if parent is set to alt, it works. (I hope more expert users can help and contribute to improve this answer, which could be helpful also for future users of ttk and tkinter).

This is my solution, where I created a complete new style:

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()

Since I am not an expert on ttk, I was not able to apply a new theme just to a certain instance of type ttk.Combobox, but I applied the theme to all instances of future possible ttk.Combobox. If someone can improve this answer, I would really appreciate the gesture!

For more information on how to create and set new styles, see here or here.

This code below worked fine for me.It is important set the order of the parameters.

`

    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())

`

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!