使用 tk.PhotoImage 在 tkinter 窗口中加载 .jpg 图像时出错

问题描述 投票:0回答:1

问题: 我正在开发一个 tkinter 应用程序,我需要在 GUI 中显示图像。虽然加载 .png 图像工作得很好,但在尝试使用

tk.PhotoImage
.

加载 .jpg 图像时遇到了困难。

这是我正在使用的代码片段:

`...
# Function for the additional button click action
def additional_function():
    try:
        image_path = "output/exp/img.jpg"
        image = tk.PhotoImage(file=image_path)
        img_label.config(image=image)
        img_label.image = image  # to keep a reference
    except Exception as e:
        print(f"Error loading image: {e}")

button2 = tk.Button(root, text="Show The Result", command=additional_function, bg="red", highlightthickness=0)
button2.config(font=("Helvetica", 14, "bold"), fg="white")
button2.place(relx=(start_x + end_x) / 2 / root.winfo_screenwidth(), rely=(sum(row_heights[:y]) + row_heights[y] + 600) / root.winfo_screenheight(), anchor=tk.CENTER)`
...`

但是,当尝试加载 .jpg 图像时,我遇到以下错误:

Error loading image: couldn't recognize data in image file "output/exp/img.JPG"

我将不胜感激任何有关解决此问题的见解或建议。预先感谢您。

python user-interface tkinter python-imaging-library yolov5
1个回答
0
投票

不幸的是,您无法加载 .jpg 图像。

来自文档

tkinter.PhotoImage(name=None, cnf={}, master=None, **kw)

可以显示 PGM、PPM、GIF、PNG 格式图像的小部件。

作为一种解决方法,我建议将图像转换为上述图像格式之一。 您可以在here轻松转换图像,也可以在Python中即时转换图像。

PIL 和 Image 是用于此目的的不错的库:

import Image
im = Image.open("file.jpg")
im.save("file.png", "PNG")
from PIL import Image
im = Image.open("file.jpg")
im.save("file.png")

如果您不喜欢在源文件旁边创建这些文件,您可以使用 tempfile 创建临时的隐藏文件。

© www.soinside.com 2019 - 2024. All rights reserved.