Python 3.7、tkinter、jpg:无法识别图像文件中的数据 [英] Python 3.7, tkinter, jpg: couldn't recognize data in image file
问题描述
我想就 python3 中的 tkinter 寻求一些帮助.我似乎无法使用以下代码在标签中显示 jpeg 图像文件:
I wanted to ask some help regarding tkinter, in python3. I can't seem to display a jpeg image file in a label using the following code:
def changephoto(self):
self.tmpimgpath = filedialog.askopenfilename(initialdir=os.getcwd())
self.installimagepath.set(self.tmpimgpath)
self.selectedpicture = PhotoImage(file=self.installimagepath.get())
self.PictureLabel.configure(image=self.selectedpicture)
它可以很好地处理 png 图像,但是当我尝试加载 jpg 图像时,我只能得到以下错误:
It can do png Images just fine, but when I try to load a jpg image, all I i am able to get is the following error:
_tkinter.TclError: couldn't recognize data in image file
我经历了所有我能找到的类似问题,但他们似乎都回答了同样的问题:from PIL import ImageTk, Image"当我尝试这样做时(目前,我正在尝试使用枕头,顺便说一句),ImageTk 似乎不可用.
I went through all similar questions I could find, but they all seem to answer the same thing: "from PIL import ImageTk, Image" When I try that ( for the moment, I am trying to use pillow, btw ), ImageTk doesn't seem to be available.
任何帮助将不胜感激.
推荐答案
你必须安装
PIL
:pip installpil
.
如果pip
没有成功安装pillow
,你可能需要尝试pip3
或pip3.7
(使用 bash 查看您有哪些选项)
If pip
does not successfully install pillow
, you might have to try pip3
or pip3.7
(use bash to see which options you have)
您可以使用 ImageTk
打开您的图像:
You can open your image with ImageTk
:
import os
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk
def changephoto():
root = tk.Tk()
PictureLabel= tk.Label(root)
PictureLabel.pack()
tmpimgpath = filedialog.askopenfilename(initialdir=os.getcwd())
selectedpicture= ImageTk.PhotoImage(file=tmpimgpath)
PictureLabel.configure(image=selectedpicture)
这篇关于Python 3.7、tkinter、jpg:无法识别图像文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!