怎样为ttk.Combobox的不同选项添加不同的背景颜色?

huangapple go评论120阅读模式
英文:

How to add different background colors to different selection options in ttk.Combobox?

问题

我想为ComboBox中的不同选择项添加不同的颜色。我找到了关于更改整体背景颜色的问题,但没有关于每个条目的问题。

我附上了一些示例如下。

怎样为ttk.Combobox的不同选项添加不同的背景颜色?
怎样为ttk.Combobox的不同选项添加不同的背景颜色?
怎样为ttk.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.

怎样为ttk.Combobox的不同选项添加不同的背景颜色?
怎样为ttk.Combobox的不同选项添加不同的背景颜色?
怎样为ttk.Combobox的不同选项添加不同的背景颜色?

答案1

得分: 0

Ttk Combobox 不支持该功能。因此,建议使用包含 EntryMenu 的自定义小部件来实现,就像在 ctk_combobox.py 中所示。

但如果你不介意修改 Tk,你可以尝试以下方法(可能会在将来出现问题):

  1. import tkinter as tk
  2. from tkinter import ttk
  3. root = tk.Tk()
  4. combo = ttk.Combobox(root, values=['red', 'green', 'blue'], state='readonly')
  5. combo.pack()
  6. def configure_items():
  7. lines = [f'set popdown [ttk::combobox::PopdownWindow {combo}]']
  8. for i, v in enumerate(combo['values']):
  9. lines.append(f'$popdown.f.l itemconfigure {i} -background {v}')
  10. root.tk.eval('\n'.join(lines))
  11. combo.configure(postcommand=lambda: root.after_idle(configure_items))
  12. root.mainloop()

要理解上述代码,你需要查看 combobox.tcllistbox 参考文档

英文:

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

  1. import tkinter as tk
  2. from tkinter import ttk
  3. root = tk.Tk()
  4. combo = ttk.Combobox(root, values = ['red', 'green', 'blue'], state = 'readonly')
  5. combo.pack()
  6. def configure_items():
  7. lines = [f'set popdown [ttk::combobox::PopdownWindow {combo}]']
  8. for i, v in enumerate(combo['values']):
  9. lines.append(f'$popdown.f.l itemconfigure {i} -background {v}')
  10. root.tk.eval('\n'.join(lines))
  11. combo.configure(postcommand=lambda: root.after_idle(configure_items))
  12. root.mainloop()

To understand the above code, you need to see the combobox.tcl and the listbox reference.

huangapple
  • 本文由 发表于 2023年3月3日 19:28:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定