Dylan Logan
Dylan Logan

Reputation: 415

Tkinter: Adding icon into menu items

I have a perfectly functional TkInter right click context menu, with 4 items and 1 separator, however I am trying to find out how to be able to display an icon with each item, I have managed to get the items to show as icons but this removes visibility of the actual text, which is not ideal. Does anyone know how to get the text to display to the right of the icon?

I will paste snippets of the code and the actual menu.

try:
    def rClick_Copy(e, apnd=0):
        e.widget.event_generate('<Control-c>')
    def rClick_Cut(e):
        e.widget.event_generate('<Control-x>')
    def rClick_Paste(e):
        e.widget.event_generate('<Control-v>')
    def rClick_SelectA(e):
        e.widget.select_range(0, 'end')
        e.widget.icursor('end')
     e.widget.focus()
     nclst=[
            ('Cut', lambda e=e: rClick_Cut(e)),
            ('Copy', lambda e=e: rClick_Copy(e)),
            ('Paste', lambda e=e: rClick_Paste(e)),
            ('Seperator', ''),
            ('Select All', lambda e=e: rClick_SelectA(e)),
            ]
     rmenu = Menu(None, tearoff=0, takefocus=0)
     for (txt, cmd) in nclst:
         if txt == 'Seperator':
             rmenu.add_separator()
             continue
         rmenu.add_command(label=txt, command=cmd,) #image=self._img4 <add this in when using icons.
     rmenu.tk_popup(e.x_root+40, e.y_root+10,entry="0")
except TclError:
    print ' - rClick menu, something wrong'
    pass

The Right Click Menu:

The Right Click Menu

The Right Click Menu With Icons:

The Right Click Menu With Icons

Upvotes: 2

Views: 4241

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385980

Like Buttons, Menubuttons, and Labels, menu items can support both text and images. To do so, you must use the compound option to tell tkinter where you want the image to appear relative to the text. The available option values are bottom, center, left, none, right and top.

For example, to get the image to appear on the left, use compound='left':

rmenu.add_command(label=txt, image=self._img4, compound='left', command=cmd)

Note: the valid positions are somewhat platform dependent. For example, on OSX the image seems to always appear to the left of the text no matter what you set compound to.

Upvotes: 3

Related Questions