英文:
How to add different background colors to different selection options in ttk.Combobox?
问题
我想为ComboBox中的不同选择项添加不同的颜色。我找到了关于更改整体背景颜色的问题,但没有关于每个条目的问题。
我附上了一些示例如下。
英文:
I want to add different colors to different selections in Combobox. I found questions about changing the overall background color, but not per entry.
I'm attaching some examples below.
答案1
得分: 0
Ttk Combobox
不支持该功能。因此,建议使用包含 Entry
和 Menu
的自定义小部件来实现,就像在 ctk_combobox.py 中所示。
但如果你不介意修改 Tk,你可以尝试以下方法(可能会在将来出现问题):
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
combo = ttk.Combobox(root, values=['red', 'green', 'blue'], state='readonly')
combo.pack()
def configure_items():
lines = [f'set popdown [ttk::combobox::PopdownWindow {combo}]']
for i, v in enumerate(combo['values']):
lines.append(f'$popdown.f.l itemconfigure {i} -background {v}')
root.tk.eval('\n'.join(lines))
combo.configure(postcommand=lambda: root.after_idle(configure_items))
root.mainloop()
要理解上述代码,你需要查看 combobox.tcl 和 listbox 参考文档。
英文:
The Ttk Combobox
does not supports that feature. So it's recommended to implement a custom widget with the Entry
and Menu
as in the ctk_combobox.py.
But if you don't mind hacking the Tk, you can try like the following.(It may break in the future.)
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
combo = ttk.Combobox(root, values = ['red', 'green', 'blue'], state = 'readonly')
combo.pack()
def configure_items():
lines = [f'set popdown [ttk::combobox::PopdownWindow {combo}]']
for i, v in enumerate(combo['values']):
lines.append(f'$popdown.f.l itemconfigure {i} -background {v}')
root.tk.eval('\n'.join(lines))
combo.configure(postcommand=lambda: root.after_idle(configure_items))
root.mainloop()
To understand the above code, you need to see the combobox.tcl and the listbox reference.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论