Reputation: 574
Apparently the ttk.Combobox dropdown listbox, which is not a ttk widget but a Tkinter Listbox, takes the system colors by default.
The example changes the background and foreground colors of the ttk.Combobox dropdown listbox in a hard-coded way when the app loads, using the option_add method. The colorize function doesn't work so it looks like I need a different method to change the color again after the app has loaded, obviously option_add() is only used once. Is there a way to change the dropdown colors dynamically? I'm using a Windows computer and Python 3.8.
I've looked at these docs but didn't find the answer:
https://wiki.tcl-lang.org/page/Changing+Widget+Colors
https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_combobox.htm
How to change background color in ttk.Combobox's listview?
import tkinter as tk
from tkinter import ttk
hbg = 'yellow'
fg = 'magenta'
def colorize(evt):
print(evt.widget.get())
bg = evt.widget.get()
root.option_add("*TCombobox*Listbox*Background", bg)
root = tk.Tk()
root.option_add("*TCombobox*Listbox*Background", hbg)
root.option_add("*TCombobox*Listbox*Foreground", fg)
c = ttk.Combobox(root, values=('red','white', 'blue'))
c.grid()
c.bind('<<ComboboxSelected>>', colorize)
root.mainloop()
Upvotes: 0
Views: 1533
Reputation: 16169
The Listbox of the Combobox is not directly accessible through Python. However this can be done using the underlying Tcl interpreter:
root.tk.eval('[ttk::combobox::PopdownWindow {}].f.l configure -background {}'.format(c, bg))
To be more convenient, you can use a custom MyCombobox
that has a config_popdown()
method to change the background and foreground of the listbox easily:
import tkinter as tk
from tkinter import ttk
hbg = 'yellow'
fg = 'magenta'
class MyCombobox(ttk.Combobox):
def config_popdown(self, **kwargs):
self.tk.eval('[ttk::combobox::PopdownWindow {}].f.l configure {}'.format(self, ' '.join(self._options(kwargs))))
def colorize(evt):
print(evt.widget.get())
bg = evt.widget.get()
evt.widget.config_popdown(background=bg)
root = tk.Tk()
root.option_add("*TCombobox*Listbox*Background", hbg)
root.option_add("*TCombobox*Listbox*Foreground", fg)
c = MyCombobox(root, values=('red', 'white', 'blue'))
c.grid()
c.bind('<<ComboboxSelected>>', colorize)
root.mainloop()
Upvotes: 1