python-3.x 使用Tkinter显示图像时出错

igetnqfo  于 2023-01-27  发布在  Python
关注(0)|答案(3)|浏览(182)

我试着运行代码:

from tkinter import *

root = Tk()
root.geometry('644x434')
root.minsize(500,200)
root.maxsize(1600,900)
photo = PhotoImage(file='1.jpg')
label1 = Label(image=photo)
label1.pack()

root.mainloop()

但是有很多错误

Traceback (most recent call last):
  File "C:/work_in_py/intro-tkinter/tkinter-/tkinter-intro.py", line 6, in <module>
    photo = PhotoImage(file='1.jpg')
  File "C:\python\lib\tkinter\__init__.py", line 4061, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\python\lib\tkinter\__init__.py", line 4006, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "1.jpg"

Process finished with exit code 1

为什么我不能显示这个图像?

w9apscun

w9apscun1#

tkinter PhotoClass不支持jpg:https://docs.python.org/3/library/tkinter.html#images
如果你需要其他格式,文档建议你使用pillow library。这个类可以作为替代:https://pillow.readthedocs.io/en/4.2.x/reference/ImageTk.html#PIL.ImageTk.PhotoImage
或者将图像保存为tkinter直接支持的格式之一:PGM、PPM、GIF和PNG格式。

fnatzsnv

fnatzsnv2#

from tkinter import *        
from PIL import ImageTk, Image

app_root = Tk()
img = ImageTk.PhotoImage(Image.open("/Users/bigbounty/Downloads/1.jpg"))
imglabel = Label(app_root, image=img).grid(row=1, column=1)        
app_root.mainloop()
jjhzyzn0

jjhzyzn03#

您的图像类型似乎是问题所在,因为不支持 jpg。请将图像类型更改为 png,它应该可以工作。

from tkinter import *
ws = Tk()
ws.title('PythonGuides')
ws.geometry('500x300')
ws.config(bg='yellow')

img = PhotoImage(file="1.png")
label = Label(
    ws,
    image=img
)
label.place(x=0, y=0)

text = Text(
    ws,
    height=10,
    width=53
)
text.place(x=30, y=50)

button = Button(
    ws,
    text='SEND',
    relief=RAISED,
    font=('Arial Bold', 18)
)
button.place(x=190, y=250)

ws.mainloop()

相关问题