【问题标题】:Tkinter: Adding icon into menu itemsTkinter:将图标添加到菜单项中
【发布时间】:2019-08-26 01:28:41
【问题描述】:

我有一个功能完善的 TkInter 右键单击​​上下文菜单,有 4 个项目和 1 个分隔符,但是我试图找出如何能够为每个项目显示一个图标,我已经设法让项目显示为图标,但这会消除实际文本的可见性,这并不理想。有谁知道如何让文字显示在图标的右侧?

我将粘贴代码的 sn-ps 和实际菜单。

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

右键菜单:

带有图标的右键菜单:

【问题讨论】:

  • 使用.add_command(..., image=self.image, compound="left"),阅读The Tkinter Button Widget - Section compound
  • @stovfl 感谢您的评论!我有一个想法,我最终会使用复合来移动图像,就像在按钮上一样。但是我没有时间测试这个。再次感谢您:)
  • 这里有一些其他(更好的)documentation 描述了Menu 项目创建选项(特别是compound 选项)。
  • @martineau 谢谢你分享这个,我不知道你可以用复合菜单项!

标签: python python-2.7 user-interface tkinter tkinter-menu


【解决方案1】:

与按钮、菜单按钮和标签一样,菜单项可以同时支持文本和图像。为此,您必须使用 compound 选项告诉 tkinter 您希望图像相对于文本显示在哪里。可用的选项值为底部、中心、左侧、无、右侧和顶部。

例如,要让图像出现在左侧,请使用compound='left'

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

注意:有效位置在某种程度上取决于平台。例如,在 OSX 上,无论您将 compound 设置为什么,图像似乎总是出现在文本的左侧。

【讨论】:

  • +1,非常感谢您的回答。我以为你可能已经能够使用复合,但我没有尝试它,因为我没有时间,现在让它工作,成功构建了一个便携式 TkInter 右键单击​​文本菜单!
  • @Dylan:在本网站提问之前,您应该先尝试一下。
  • 我想是的,我知道下次。无论如何,谢谢你的帮助。
猜你喜欢
  • 2012-11-01
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
相关资源
最近更新 更多