【问题标题】:Why Isn't My Image Showing With Tkinter?为什么我的图像没有用 Tkinter 显示?
【发布时间】:2018-09-08 15:53:24
【问题描述】:

Following this answer,我正在尝试显示要显示的图像,但是当我去运行它时(几乎与答案中的完全一样),窗口不显示图像。

from PIL import Image
import tkinter

window = tkinter.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
imageFile = "/Users/glennsha/Desktop/APCS_Create/Rank_icons/champion1.jpg"
window.im1 = Image.open(imageFile)

input()
window.mainloop()

【问题讨论】:

  • 您复制了问题格式,但没有在该问题的答案中使用img = ImageTk.PhotoImage(Image.open(path))。尝试将此部分添加到您的代码中,并将实际的图像小部件添加到框架中。
  • 那么,您从一个工作示例中删除了代码,但现在它不起作用?您是否考虑过可能删除了一些重要的部分?

标签: python python-3.x image tkinter jpeg


【解决方案1】:

只需在您引用的同一链接中关注answer。 我在相关部分添加了解释以帮助您理解。您可以阅读有关ImageImageTk here 的更多信息。

from PIL import Image, ImageTk # I have added the import of ImageTk 
import tkinter

window = tkinter.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
imageFile = "/Users/glennsha/Desktop/APCS_Create/Rank_icons/champion1.jpg"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
im1 = ImageTk.PhotoImage(Image.open(imageFile))

#Next, you need to put your image into a widget before it can be visible.
# Your reference answer used a Label widget. We will use the same here.
# This Label widget is a child of "window" which is the Tk() window. 
panel = tkinter.Label(window, image = im1)

#Next you need to put the widget into the Tk() window before the widget can be made visible.
# Here, the Pack geometry manager is used to put/locate the widget containing
# the images into the Tk() Window.
panel.pack(side = "bottom", fill = "both", expand = "yes")

window.mainloop()

【讨论】:

  • 您应该编辑掉您的文件路径并保留 OPs 文件路径。没有理由同时显示两者。
  • @Mike-SMT 感谢您的提醒。用它来测试。忘记删除了。
猜你喜欢
  • 2019-12-10
  • 1970-01-01
  • 2021-08-08
  • 2021-10-10
  • 1970-01-01
  • 2019-04-28
  • 2014-08-06
  • 2016-07-12
  • 2021-03-31
相关资源
最近更新 更多