【发布时间】:2026-02-15 10:30:02
【问题描述】:
显然 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
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()
【问题讨论】: