'How to change menu background color of Tkinter's OptionMenu widget?
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
Solution 1:[1]
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()
Solution 2:[2]
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:
With Tkinter the command to set attributes to the window without it being clicked is:
w.config(bg="GREEN")
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...
As well as the ugly blue color:
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! :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bryan |
Solution 2 | Astrium |