简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM