python - 图像“pyimage4”不存在
问题描述
我是 Tkinter 新手,这是我在互联网上找到的基本图像显示代码。
import tkinter as tk
from PIL import ImageTk, Image
path = r'.\0030001621.jpg'
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
这给出了这个错误:
---------------------------------------------------------------------------
TclError Traceback (most recent call last)
<ipython-input-10-ed688d6a5ab6> in <module>
7 root = tk.Tk()
8 img = ImageTk.PhotoImage(Image.open(path))
----> 9 panel = tk.Label(root, image = img)
10 panel.pack(side = "bottom", fill = "both", expand = "yes")
11 root.mainloop()
c:\users\fatima.arshad\appdata\local\continuum\anaconda2\envs\web_scraping\lib\tkinter\__init__.py in __init__(self, master, cnf, **kw)
2764
2765 """
-> 2766 Widget.__init__(self, master, 'label', cnf, kw)
2767
2768 class Listbox(Widget, XView, YView):
c:\users\fatima.arshad\appdata\local\continuum\anaconda2\envs\web_scraping\lib\tkinter\__init__.py in __init__(self, master, widgetName, cnf, kw, extra)
2297 del cnf[k]
2298 self.tk.call(
-> 2299 (widgetName, self._w) + extra + self._options(cnf))
2300 for k, v in classes:
2301 k.configure(self, v)
TclError: image "pyimage4" doesn't exist
我该如何解决这个问题?
解决方案
首先确保您为图像提供了正确的路径。
然后试试下面的方法,
尝试保持图像对 Tkinter 对象的引用。
import tkinter as tk
from PIL import ImageTk, Image
path = r'mposter.jpg'
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
# keep a reference
panel.image = img
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
您可以更详细地了解这一点
http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
推荐阅读
- html - Angular-是否可以在子组件中使用内容投影?
- docker - 如何在 IntelliJ 中启动 Docker 后启动浏览器
- amazon-web-services - 如何通过 AWS SNS 发送电子邮件,每条消息都有一个自定义 FROM 地址
- python - 如何在 Python 中生成新的排列?
- python - 在生产环境中使用 Sanic 的内置网络服务器
- mysql - 如何按月创建活跃公司的视图?
- html - 如何提高我的网站在移动设备上的可读性?
- cvs - cvs 在 MacOs-Catalina 上坏了?(无法获取工作目录)
- google-apps-script - 有没有办法让谷歌表单响应在具有多个页面的工作表上进行格式化和排序
- validation - 在 Azure B2C 社交注册 [api.selfasserted] 验证期间显示的 verifying_blurb 文本保留在屏幕上