【问题标题】:Python Tkinter - Menu icon doesn't showPython Tkinter - 菜单图标不显示
【发布时间】:2018-02-08 02:35:33
【问题描述】:

我正在使用 tkinter 构建菜单,但图标不显示。 你能帮帮我吗?

mb=Menu(w)
w.config(menu=mb)
fm=Menu(mb,tearoff=0)
om=Menu(mb,tearoff=0)
hm=Menu(mb,tearoff=0)
mb.add_cascade(label=_("File"),menu=fm)
fm.add_command(label=_("Esci"), image=PhotoImage(r"icons\exit.png"),
               compound="left",command=w.destroy)
fm.iconPhotoImage = PhotoImage(r"icons\exit.png")
mb.add_cascade(label=_("Opzioni"),menu=om)
om.add_command(label=_("Impostazioni"), image=PhotoImage(r"icons\settings.png"),
               compound="left", command=settings.creaFinestra)
om.add_command(label=_("Cambia lingua"), image=PhotoImage(r"icons\language.png"),
               compound="left", command=settings.cambiaLingua)
mb.add_cascade(label=_("Aiuto"), menu=hm)
hm.add_command(label=_("Guida"), image=PhotoImage(r"icons\help1.png"),
               compound="left",
               command= lambda: webbrowser.open("https://github.com/maicol07/school_life_diary_pc/wiki"))
hm.add_command(label=_("Informazioni"), image=PhotoImage(r"icons\help.png"),
               compound="left",command=info)

【问题讨论】:

  • 您可以尝试在主窗口小部件中显示其中一张图片吗?只需在您的代码中添加Label(w, image=PhotoImage(r"icons\settings.png")).pack()。如果不显示,则问题出在图像创建本身。

标签: python python-3.x tkinter menu


【解决方案1】:

正如here 解释的那样,对于此类图像格式,您需要使用PIL 库,该库将它们转换为与 Tkinter 兼容的图像对象

from PIL import Image, ImageTk

image = Image.open("icons\exit.png")
photo = ImageTk.PhotoImage(image)

然后将其附加到您的小部件:

fm.add_command(label=_("Esci"), image=photo, ...)

您需要对您使用的每个 .png 图像重复此过程。

【讨论】:

  • 但是我使用带有 PhotoImage 功能的图像以及其他小部件......请注意,我使用的是 Python 3.6.2
  • png 在当前版本的 tkinter 中得到支持。
  • 是的,我不知道 OP 使用的是哪个版本,但由于他没有显示它们,我想他的版本不是那么新。 @SierraMountainTech
  • 我刚刚注意到 OP 评论说他正在使用 3.6.2,并认为我会提出一些与 OP 问题相关的信息
  • 在同一个屏幕上,我有另一个 png 图像。在另一个文件中,我添加了三个按钮,每个按钮都有一个图像。问题是这些图片没有显示出来……现在给大家分享完整代码
猜你喜欢
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多