开发者

Different color for different choices in tkinter option menu

I am using Python and Tkinter. I have an option menu with three choices with "on" being one of them. I want to make "on" be green when I select it. I don't mean the font. I want the background of the option menu to be green when I select "on" while the other options will just be default gray.

How can I do this? I've seen other posts that just make the whole option menu background a different color, but I only want color when a p开发者_如何学Carticular choice is selected. Thank you!


file this under U, for ugly:

from Tkinter import *

OPTIONS = (
    "egg",
    "go",
    "spam"
)

controlsMap = {}

root = Tk()

def callbackFunc(name, index, mode):
    value = root.getvar(name) #getvar: return the value of Tcl variable NAME
    widget = controlsMap[name]
    if value == 'go':
        widget.config(bg='green',fg='black',
                 activebackground='green',
                 activeforeground='black')
    else:
        widget.config(bg='SystemButtonFace',fg='SystemButtonText',
                 activebackground='SystemButtonFace',
                 activeforeground='SystemButtonText')


var1 = StringVar(root, name='var1') #give it a master and a name
var1.set(OPTIONS[0])
om1 = OptionMenu(root, var1, *OPTIONS)
om1.config(width=5)
om1.grid(row=0, column=0)
controlsMap['var1'] = om1
var1.trace_variable('w', callbackFunc)

var2 = StringVar(root, name='var2') #
var2.set(OPTIONS[0])
om2 = OptionMenu(root, var2, *OPTIONS)
om2.config(width=5)
om2.grid(row=0, column=1)
controlsMap['var2'] = om2
var2.trace_variable('w', callbackFunc)

var3 = StringVar(root, name='var3') #
var3.set(OPTIONS[0])
om3 = OptionMenu(root, var3, *OPTIONS)
om3.config(width=5)
om3.grid(row=0, column=2)
controlsMap['var3'] = om3
var3.trace_variable('w', callbackFunc)


root.mainloop()


you could put a trace on it:

from Tkinter import *

OPTIONS = (
    "egg",
    "go",
    "spam"
)

root = Tk()

var = StringVar()
var.set(OPTIONS[0]) # default

def callbackFunc(name, index, mode):
    value = var.get()
    if value == 'go':
        om.config(bg='green',fg='black',
                 activebackground='green',
                 activeforeground='black')
    else:
        om.config(bg='SystemButtonFace',fg='SystemButtonText',
                 activebackground='SystemButtonFace',
                 activeforeground='SystemButtonText')

om = OptionMenu(root, var, *OPTIONS)
om.pack()

Callbackname = var.trace_variable('w', callbackFunc)

root.mainloop()


If you are on windows you are out of luck because menus are native controls which don't allow this much customization. The same might be true for osx, but I don't remember for certain.

For other platforms you can use the entryconfigure method of the menu associated with the option menu, which lets you set the background color of each entry in the menu.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜