Skip to content
Advertisement

ttk:Combobox foreground color change doesn’t work properly. What’s wrong?

Attemps to reliably change the text color in a ttk::Combobox fail. It happens for me on Windows 10 with the native theme.

The following code creates two comboboxes with their foreground color set to red. Selecting an option in one of them then the other, back and forth, shows that the foreground color alternates between black and red.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
ttk.Style().configure('Red.TCombobox', foreground='red')
combo = ttk.Combobox(root, values=('one', 'two', 'three'), state='readonly')
combo.configure(style='Red.TCombobox')
combo.grid(row=0, column=0)
combo2 = ttk.Combobox(root, values=('one', 'two', 'three'), state='readonly')
combo2.configure(style='Red.TCombobox')
combo2.grid(row=0, column=1)
root.mainloop()

Here’s what it looks like:

combo foreground color illustration

How can I make it red at least when the text is not marked as selected? (a solution for the selected text would be appreciated as well)

Advertisement

Answer

Try modifying your Style instance from:

ttk.Style().configure('Red.TCombobox', foreground='red')

to:

ttk.Style().map(
    'Red.TCombobox',
    foreground=[('readonly', 'red')],
    selectforeground=[('readonly', 'red')],
)

Using map() here allows you to specify a “statespec” (i.e., the widget state to which your style applies) – you can read more here

BONUS – COLORING THE LIST ITEMS:

If you want all of your list items to be red, you (unfortunately) can’t use the Style() class. Instead, you can use Tk.option_add – you can read more here (scroll up a bit to the ‘Note’ just above “Create a custom style”)

In this case, you’ll want to add

root.option_add('*TCombobox*Listbox.foreground', 'red')

anywhere before root.mainloop() (preferably just after root = tk.Tk())

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement