How to change menu background color of Tkinter's OptionMenu widget?
Asked Answered
C

2

15

If I take a simple example of OptionMenu from http://effbot.org/tkinterbook/optionmenu.htm, and add a line that sets background color (see below), only the button background changes color, not the drop-down menu which remains gray. Can I set color for both the button and the menu of OptionMenu?

I am using Windows 7, Python 2.6.6, Tkinter Rev 73770

from Tkinter import *  
master = Tk()  
variable = StringVar(master)  
variable.set("one") # default value  
w = OptionMenu(master, variable, "one", "two", "three")  
w.config(bg = "GREEN")  # Set background color to green  
w.pack()  
mainloop()  

Thank you

Corporative answered 30/5, 2011 at 15:29 Comment(0)
G
24

You need to grab the menu object from the OptionMenu and set its background color. This should accomplish what you want...

w = OptionMenu(master, variable, "one", "two", "three")  
w.config(bg = "GREEN")  # Set background color to green

# Set this to what you want, I'm assuming "green"...
w["menu"].config(bg="GREEN")

w.pack()  
Gentlefolk answered 30/5, 2011 at 16:28 Comment(1)
On M1 using 3.10.0b1, you don't have to include the object via ["menu"] but still need to configure after initialisation.Diamagnetism
C
6

I add my answer a little late but I would like to add a clarification!

As @Bryan well said, the command to change the background and foreground color is fine:

 w["menu"].config(bg="GREEN")

But this command actually only affects the drop-down menu when clicked, as can be seen in this image:

Drop-down menu background color only when clicked

With Tkinter the command to set attributes to the window without it being clicked is:

w.config(bg="GREEN")

Drop-down menu background color without it being clicked

It's therefore necessary to combine the two lines of code to have a completely green drop-down menu!

w.config(bg="GREEN")
w["menu"].config(bg="GREEN")

But there is still a problem because if you put your cursor on the button to open the menu then it resumes its default white color...

Drop-down menu background color when cursor above

As well as the ugly blue color:

Drop-down menu background color when cursor above

Fortunately there is a parameter for the .config() function to correct this problem:

w.config(bg="GREEN", fg="BLACK", activebackground="GREEN", activeforeground="BLACK")
w["menu"].config(bg="GREEN", fg="BLACK", activebackground="GREEN", activeforeground="BLACK")

So here is the method to have a green drop-down menu in the background and black for the menu entries. But you can modify the parameters of the .config() function as you wish! (like width, height, font, font size,...)

I hope I was understanding enough for beginners in Tkinter like me! :)

Chukar answered 19/4, 2022 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.