首页 > 解决方案 > 图像“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

我该如何解决这个问题?

标签: pythontkinter

解决方案


首先确保您为图像提供了正确的路径。

然后试试下面的方法,

尝试保持图像对 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


推荐阅读