![](/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.