You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter的Combobox下拉列表能否为特定选项设置自定义颜色?

Tkinter Combobox下拉项单独着色实现方案

可以实现该需求,ttk.Combobox没有公开的单选项着色API,但可以通过操作其下拉列表对应的隐藏Listbox控件完成配置。

完整可运行代码

import tkinter as tkp
from tkinter import ttk
from tkinter import messagebox

window = tkp.Tk()
window.geometry("600x500")

def set_dropdown_color(event):
    # 获取Combobox的下拉弹窗对象
    popdown = txtCityName.tk.call("ttk::combobox::popdown", txtCityName)
    # 从弹窗中获取Listbox控件
    listbox = txtCityName.nametowidget(f"{popdown}.f.l")
    # 遍历所有选项设置颜色
    for idx, city in enumerate(cities):
        if city in ("OIHH", "OISS"):
            listbox.itemconfig(idx, foreground="red")
        else:
            listbox.itemconfig(idx, foreground="blue")

def set_selected_color(event):
    # 选中后同步修改输入框内的文字颜色
    selected = txtCityName.get()
    if selected in ("OIHH", "OISS"):
        txtCityName.config(foreground="red")
    else:
        txtCityName.config(foreground="blue")

if __name__ == "__main__" :
    cities = ['OIII','OITT','OIHH','OISS','OIBB']
    txtCityName = ttk.Combobox(window, width = 13, height=15, values=cities, font='sans 10 bold')
    # 绑定下拉弹出事件,设置下拉项颜色
    txtCityName.bind("<<ComboboxPopdown>>", set_dropdown_color)
    # 绑定选中事件,同步输入框颜色
    txtCityName.bind("<<ComboboxSelected>>", set_selected_color)
    txtCityName.pack()
    window.mainloop()

说明

  • 核心逻辑:ttk.Combobox的下拉菜单本质是独立弹窗中的Listbox控件,绑定<<ComboboxPopdown>>事件后,每次下拉弹出时会遍历所有选项按规则着色
  • 如果不需要同步输入框的文字颜色,删除set_selected_color函数和对应的绑定代码即可
  • 上述代码适配Python 3.x的标准Tkinter环境,可在Windows、macOS、主流Linux发行版正常运行

内容的提问来源于stack exchange,提问作者morteza hosseini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 21:15:03