簡體   English   中英

tkinter.TclError:無法識別圖像文件中的數據

[英]tkinter.TclError: couldn't recognize data in image file

我目前正在錄制Python講座中,我認為老師使用的python版本已過時,他正在編寫tkinter程序,但是在復制后,我仍然遇到此錯誤:

Traceback (most recent call last):
  File "C:\Users\1234\AppData\Local\Programs\Python\Python36-32\Lecture Class 11.py", line 35, in <module>
    photo = PhotoImage(file="Me With My 5th Place.jpg")
  File "C:\Users\1234\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3539, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\1234\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3495, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "Me With My 5th Place.jpg"

這是我的代碼:

from tkinter import *

class Application(Frame):
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.button_clicks = 0
        self.create_widgets()

    def create_widgets(self):
        self.label1 = Label(self)
        label1.image = photo
        label1.grid()
        self.button1 = Button(self)
        self.button1["text"] = "Click me!!!"
        self.button1["command"] = self.update_count
        self.button1.grid(row=1, column=1)
        self.button2 = Button(self)
        self.button2["text"] = "Reset click counter"
        self.button2["command"] = self.reset_count
        self.button.grid(row=3, column= 1)

    def update_count(self):
        self.button_clicks += 1
        self.button1["text"] = "Total clicks: " + str(self.button_clicks)

    def res_count(self):
        self.button_clicks = 0
        self.button["text"] = "I am reset. Click me!!!"

root = Tk()
root.title("CP101 click counter")
root.geometry("400x400")

photo = PhotoImage(file="Me With My 5th Place.jpg")

app = Application(root)

root.mainloop()

默認情況下, tkinter不支持.jpg。 您可以使用PIL使用.jpg文件:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except:
    import Tkinter as tk
from PIL import Image, ImageTk


if __name__ == '__main__':
    root = tk.Tk()

    label = tk.Label(root)
    img = Image.open(r"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg")
    label.img = ImageTk.PhotoImage(img)
    label['image'] = label.img

    label.pack()
    root.mainloop()

這是很正常的。 Tkinter尚不支持.jpg文件。 要解決該問題,您需要將文件轉換為.png,.gif或類似文件,或者使用枕頭模塊添加對.jpg文件的支持。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM