1

I'm trying to write a code to change the color of a specific option in ttk.OptionMenu with press of a button (only that option should appear with the color when seen in the drop down). Here is a code similar to my need.

from tkinter import *
from tkinter.ttk import OptionMenu

root = Tk()

def ch_color():
    global ent, options
    option = ent.get()
    if option in options:
        #The code to change the color of that option in opt_menu

options = ['option 1','option 2', 'option 3', 'option 4']

var = StringVar()
var.set("Select")
opt_menu = OptionMenu(root, var, *options).pack()

ent = StringVar()
entry = Entry(root, textvariable = ent).pack()
button = Button(root, text = "Change Color", command = ch_color).pack()

I've tried this, but apparently it changes the color of the entire widget, and not a specific option, and this, but this doesn't work on Windows. Any help will be appreciated.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
astqx
  • 2,058
  • 1
  • 10
  • 21
  • 1
    Does this answer your question? [How to change menu background color of Tkinter's OptionMenu widget?](https://stackoverflow.com/questions/6178153/how-to-change-menu-background-color-of-tkinters-optionmenu-widget) – Aka Aug 27 '20 at 20:43
  • Thanks for your effort, I've figured it out already. – astqx Aug 28 '20 at 11:55

1 Answers1

1

The OptionMenu is a button that shows a menu. The menu is a Tk menu so you can use menu commands on it once you fetch a reference from the OptionMenu widget. eg:

menu = opt_menu.nametowidget(opt_menu.cget('menu'))
index = menu.index('option 2')
menu.entryconfigure(index, background='red')

This will find the menu index of the 'option 2' entry and change its background color.

Personally I recommend using the ttk.Combobox instead.

patthoyts
  • 32,320
  • 3
  • 62
  • 93
  • Thanks a lot for the quick reply, works perfectly. Also, thank you for the suggestion to use `ttk.Combobox` – astqx Aug 13 '20 at 04:57