鬼少 发表于 2025-1-4 15:17:25

为什么PhotoImage读取不到图片,只能显示窗口文字

from tkinter import *

root = Tk()

textLabel = Label(root,text ='您所下载的影片含有未成年限制内容,请满18周岁后再点击')
textLabel.pack()

photo = PhotoImage(file="D:\program\python_code\1.jpeg")
imgLabel = Label(root,image=photo)

imgLabel.pack()

mainloop()


代码执行后不能显示路径下的 1.jpeg图片并提示如下错误:

=================== RESTART: D:\program\python_code\image.py ===================
Traceback (most recent call last):
File "D:\program\python_code\image.py", line 8, in <module>
    photo = PhotoImage(file="D:\program\python_code\1.jpeg")
File "D:\program\Python\Python312\Lib\tkinter\__init__.py", line 4162, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
File "D:\program\Python\Python312\Lib\tkinter\__init__.py", line 4109, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "D:\program\python_code.jpeg": no such file or directory

FishC 发表于 2025-1-4 15:17:44

根据您提供的信息,问题可能是由于文件路径中的反斜杠 `\` 造成的。反斜杠在字符串中是转义字符,`\1` 会被解释为特殊字符,这导致路径出错。可以通过使用双反斜杠 `\\` 或者将路径前缀为 `r` 表示原始字符串来解决这个问题。

请尝试以下其中一种修改:

1. 使用双反斜杠 `\\`:
   photo = PhotoImage(file="D:\\program\\python_code\\1.jpeg")

2. 使用原始字符串:
   photo = PhotoImage(file=r"D:\program\python_code\1.jpeg")

这样,路径中的反斜杠将被正确识别为路径分隔符,而不是转义字符。请修改后再试一下。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

鬼少 发表于 2025-1-4 15:22:45

FishC 发表于 2025-1-4 15:17
根据您提供的信息,问题可能是由于文件路径中的反斜杠 `\` 造成的。反斜杠在字符串中是转义字符,`\1` 会被 ...

使用原始字符串后又包这样的错误
Traceback (most recent call last):
File "D:\program\python_code\image.py", line 9, in <module>
    photo = PhotoImage(file=r"D:\program\python_code\1.jpeg")
File "D:\program\Python\Python312\Lib\tkinter\__init__.py", line 4162, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
File "D:\program\Python\Python312\Lib\tkinter\__init__.py", line 4109, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "D:\program\python_code\1.jpeg"

FishC 发表于 2025-1-4 15:22:54

鬼少 发表于 2025-01-04 15:22
FishC 发表于 2025-1-4 15:17
根据您提供的信息,问 ...

`PhotoImage` 只能处理 GIF 和 PNG 格式的图片,而您尝试加载的是 JPEG 文件。要解决这个问题,您可以使用 `PIL`(Python Imaging Library)中的 `Image` 模块来处理 JPEG 图片。

请先确保已安装 `PIL` 库(或 `Pillow`,它是 `PIL` 的派生版本)。可以使用以下命令安装:

pip install Pillow

然后修改您的代码如下:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

textLabel = Label(root, text='您所下载的影片含有未成年限制内容,请满18周岁后再点击')
textLabel.pack()

# 使用 PIL 打开 JPEG 文件,并转换成 PhotoImage
image = Image.open(r"D:\program\python_code\1.jpeg")
photo = ImageTk.PhotoImage(image)

imgLabel = Label(root, image=photo)
imgLabel.pack()

mainloop()

这样修改后,您的程序就能够处理 JPEG 文件了。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: 为什么PhotoImage读取不到图片,只能显示窗口文字