1
votes

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

1
Use .add_command(..., image=self.image, compound="left"), read The Tkinter Button Widget - Section compound - stovfl
@stovfl Thank you for the comment! I had an idea that I'd end up using compound to shift the images round, like on a button. But I haven't had time to test this. Thank you once again :) - Dylan Logan
Here's some other (better) documentation that describes the Menu item creation options (specifically the compound option). - martineau
@martineau Thank you for sharing this, I didn't know you could use compound with menu items! - Dylan Logan

1 Answers

2
votes

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.