繁体   English   中英

使用Tkinter在Python中插入一张JPG图片

[英]Insert an JPG image in Python using Tkinter

我正在尝试使用 Tkinter 插入图像但它不起作用,有一条错误消息说:(实际上它是说 python 无法识别图像文件中的数据)

Traceback (most recent call last):
  File "E:/Tle/ISN/Programs (Pyhton)/IMC (Widget) ULTIMATE.py", line 10, in <module>
    my_image = PhotoImage(file="C:/Users/mateo.PCMATEO/Pictures/MonCoachPersonnel.jpg")
  File "C:\Users\mateo.PCMATEO\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3545, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\mateo.PCMATEO\AppData\Local\Programs\Python\Python37-32\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/mateo.PCMATEO/Pictures/MonCoachPersonnel.jpg"

这是我输入的代码:

from tkinter import*
import tkinter as tk
window = tk.Tk()
window.title("My Personnal Fitness Coach")
window.geometry("400x500")
window.configure(background='grey')

canvas = Canvas(window, width = 100, height = 100)
canvas.pack
my_image = PhotoImage(file="C:/Users/mateo.PCMATEO/Pictures/MonCoachPersonnel.jpg")
canvas.create_image(0, 0, anchor = NW, image=my_image)

window.mainloop()

问题是我没有任何模块,除了用 python 预下载的模块,我还不想安装一些模块。 那你能帮我吗?

如果你使用 jpg 你必须这样做

from PIL import ImageTk

然后

my_image = ImageTk.PhotoImage(file="MonCoachPersonnel.jpg")
canvas.create_image(50, 50, image=my_image, anchor=NW)

我已经简化了文件目录,请注意我已经将图片的尺寸从 0,0 增加到 50,50。

请试试这个(只更改图像文件路径)

from tkinter import*
import tkinter as tk
from PIL import ImageTk, Image


window = tk.Tk()
window.title("My Personnal Fitness Coach")
window.geometry("400x500")
window.configure(background='grey')

canvas = Canvas(window, width = 100, height = 100)
canvas.pack()

photo_image = ImageTk.PhotoImage(Image.open('xxxx\\racecar.jpg'))
my_image = canvas.create_image(0, 0, image=photo_image, anchor=NW) 

# my_image = PhotoImage(file="xxxx\\racecar.jpg")
# canvas.create_image(0, 0, anchor = NW, image=my_image)

window.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM