简体   繁体   中英

How to change ttk.Combobox dropdown colors dynamically

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM