更改tk选项菜单中单个单词的颜色?

时间:2017-07-24 19:07:31

标签: python macos python-2.7 tkinter

所以我抓住网站上的活动链接并将它们放入下拉菜单中进行选择。我的菜单代码:

import Tkinter as tk     
from Tkinter import StringVar

selectMenu = tk.Tk()


# #-> this is what I have
# Followed by what you can use


#var = Vars()
#events = var.GetVars('Event')
events = " "
options = []
links = []
#forms = (driver.find_elements_by_class_name("with-cats")) #This is what I have
forms = ["Yolo ","Dad? Closed","Anotha One","Normies! Closed"] #This is so you can try it for yourself

for x in forms:
    #info = x.text
    info = x #Again, this is so you can try it for yourself
    if events in info.lower():
        links.append(x)

for link in range(0,len(links)):
    #options.append(links[link].text)
    options.append(links[link])
list(set(options))

selection = []
for link in range(0,len(options)):
    selection.append(options[link])
select = StringVar(selectMenu)
select.set("--None Selected--")

menu = tk.OptionMenu(selectMenu, select, *(selection))

msg = "Which one would you like to attend?"
label = tk.Label(selectMenu, text=msg, font="Helvedica 14")

label.pack(side='top', pady=10)
menu.pack(side="top", pady=10)     

selectMenu.attributes('-topmost', True)
selectMenu.mainloop()   

所以这样做工作得很好,但是我希望改进外观以使哪些事件更加明显。为了澄清,发现打开并放入菜单的事件可能看起来像“这是一个很酷的事件”,但关闭的事件将被解读为“这是一个很酷的事件已关闭”。我的目标是能够使前景红色只是单词Closed或包含Closed的字符串,无论哪个都可能(我不确定是否可能,因为osx上的菜单和按钮通常默认为系统设置,也许有办法解决这个问题?)。

           Current:                        Desired:

3 个答案:

答案 0 :(得分:1)

根据OptionMenu herehere的文档,我认为没有办法设置文字的颜色。

您可以通过使用listBox来获得您想要的东西。有关listBox示例,请参阅帖子here

答案 1 :(得分:1)

找到解决方案!使用MenuButton内部的菜单与Tkinter创建MenuOptions的方式相同,我能够创建自定义MenuOption。如果您想添加更多选项,可以使用menbutton.configure()选项编辑按钮,使用menbutton.menu编辑菜单项。

import Tkinter as tk     
from Tkinter import Menu, Menubutton

class Vars():

    global vari
    vari = {}

    def GetVars(self, var):

        return vari.get(str(var))

    def SendVars(self, var, val):

        vari[str(var)] = val


class App():

    def buttselect(self, link, menbutton, selectMenu):
        var = Vars()
        var.SendVars("Selection", link) # Store selected event
        menbutton.configure(text=link) # Set menu text to the selected event

    def prnt(self, link):
        var = Vars()

        print var.GetVars("Selection") # Print event

    def __init__(self, selectMenu):
        events = " "
        options = []
        links = []
        forms = ["Yolo ","Dad? Closed","Anotha One","Normies! Closed"] #This is so you can try it for yourself

        menbutton =  Menubutton (selectMenu, text="--None Selected--", relief="raised")
        menbutton.grid()
        menbutton.menu  =  Menu (menbutton, tearoff=0)
        menbutton["menu"]  =  menbutton.menu

        #Get a list of event names
        for x in forms:
            info = x #Again, this is so you can try it for yourself
            #If desired event keyword is in an event name, add it to the correct links
            if events in info.lower():
                links.append(x)

        #Remove duplicates
        for link in range(0,len(links)):
            options.append(links[link])
        list(set(options))

        #Final list of event names turned into menu commands
        for link in options:

            if "Closed" in link:
                menbutton.menu.add_command( label= link, command= lambda link=link: self.buttselect(link, menbutton, selectMenu), foreground='red')
            else:
                menbutton.menu.add_command( label= link, command= lambda link=link: self.buttselect(link, menbutton, selectMenu))

        b = tk.Button(selectMenu, text="Selection", command= lambda link=link: self.prnt(link)) #Print selected event
        b.pack()

        msg = "Which one would you like to attend?"
        label = tk.Label(selectMenu, text=msg, font="Helvedica 14")

        label.pack(side='top', pady=10)
        menbutton.pack(side="top", pady=10)     


selectMenu = tk.Tk()
selectMenu.attributes('-topmost', True)
app = App(selectMenu)
selectMenu.mainloop()   

这导致了所需的结果:

答案 2 :(得分:0)

我找到了方法!

假设x是带有选项的选项菜单:

options=['Red','Blue','Green']

defopt=tk.StringVar(options[0])   #StringVariable to hold the selected option.

x=tk.OptionMenu(self.optmenuframe,defopt,*options)

现在,从选项菜单获取菜单对象,并使用 entryconfig 方法。 就是这样!

x.children['menu'].entryconfig(0,foreground='red')
x.children['menu'].entryconfig(1,foreground='blue')
x.children['menu'].entryconfig(2,foreground='green')

#0 is the index of the option you want to apply the configurations to.