![](/img/trans.png)
[英]How to change the color of the active background of the dropdown menu (i.e. tk.Listbox) in a ttk.Combobox
[英]How to change ttk.Combobox dropdown colors dynamically
顯然,ttk.Combobox 下拉列表框不是 ttk 小部件而是 Tkinter 列表框,默認情況下采用系統顏色。
該示例使用 option_add 方法在應用加載時以硬編碼方式更改 ttk.Combobox 下拉列表框的背景和前景色。 colorize 函數不起作用,所以看起來我需要一種不同的方法在應用程序加載后再次更改顏色,顯然 option_add() 只使用一次。 有沒有辦法動態更改下拉顏色? 我使用的是 Windows 計算機和 Python 3.8。
我看過這些文檔,但沒有找到答案:
https://wiki.tcl-lang.org/page/Changing+Widget+Colors
https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_combobox.htm
如何在 ttk.Combobox 的列表視圖中更改背景顏色?
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()
組合框的列表框不能通過 Python 直接訪問。 然而,這可以使用底層的 Tcl 解釋器來完成:
root.tk.eval('[ttk::combobox::PopdownWindow {}].f.l configure -background {}'.format(c, bg))
為了更方便,您可以使用具有config_popdown()
方法的自定義MyCombobox
輕松更改列表框的背景和前景:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.