【问题标题】:Images not showing up in tkinter GUI window图像未显示在 tkinter GUI 窗口中
【发布时间】:2020-03-04 00:28:33
【问题描述】:

基本上,我在 tkinter GUI 窗口中打开图像 (.jpg) 时遇到问题。

我遵循了这个教程:https://www.youtube.com/watch?v=lt78_05hHSk

但我只是得到一个空白窗口。

from tkinter import *

root = Tk()

photo = PhotoImage(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
# photo = PhotoImage(file="123k.jpg")
label = Label(root, image=photo)
label.pack()

root.mainloop()

文件路径正确,.jpg 文件与tkinter 兼容。会发生什么?

我收到此错误

Traceback (most recent call last): 
File "C:\Users\xxx\ytrewq.py", line 5, 
in <module> photo = PhotoImage(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg") 
File "C:\Users\xxxx\AppData\Local\Programs\Thonny\lib\tkinter_init_.py", line 3545,
in init Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\xxxx\AppData\Local\Programs\Thonny\lib\tkinter_init_.py", line 3501, 
in init self.tk.call(('image', 'create', imgtype, name,) + options) 
_tkinter.TclError: couldn't recognize data in image file 
"C:\Users\xxxx\OneDrive\Desktop\123k.jpg"

【问题讨论】:

  • 请记下您收到的具体错误,并将您的图像文件另存为.png。我已经运行了你的代码,如果我尝试 jpg,我会收到错误 TclError: couldn't recognize data in image file "/Users/Siddarth/Desktop/ClMsNHW.jpg,如果我尝试 .png,我会成功
  • 错误告诉你什么问题:tkinter 不支持 jpg。
  • 请不要将代码和回溯放在 cmets 中。 edit你的问题加在那里。
  • 太棒了。 PNG文件工作。谢谢。
  • @Emilio,很高兴听到它,如果您想使用.jpg,那么我在这里推荐这篇文章 (pythonbasics.org/tkinter-image)。祝你好运。

标签: python image tkinter


【解决方案1】:

出现此错误是因为只有 PhotoImage 函数无法识别 .jpg 格式的图像。为此,您可以使用 png 格式,也可以使用

Image.open(path_of_the_file) 然后

ImageTk.PhotoImage(img_object)

对于这个 Image 和 ImageTk,你必须从 PIL 模块导入它

from PIL import Image, ImageTk

洞解代码:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

# photo = PhotoImage(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
# photo = PhotoImage(file="123k.jpg")
img = Image.open(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
photo = ImageTk.PhotoImage(img)

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

root.mainloop()

【讨论】:

    猜你喜欢
    • 2017-10-02
    • 1970-01-01
    • 2017-10-17
    • 2017-03-28
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多