|
发表于 2023-8-31 18:03:31
|
显示全部楼层
tkinter的PhotoImage()函数只能处理一些特定的图片格式,例如GIF、PGM、PPM和XBM。对于其他格式的图片,需要使用PIL(Python Imaging Library)来处理。
在你的代码中,当你尝试加载一个GIF图片时,出现了tkinter.TclError: couldn't recognize data in image file "qq.gif"的错误。这是因为tkinter的PhotoImage()函数无法识别GIF图片的数据。
要解决这个问题,你需要安装PIL库。你可以使用以下命令来安装PIL:
安装完成后,你需要将导入语句改为:
- from PIL import Image, ImageTk
复制代码
然后,你可以使用PIL库中的Image.open()函数来打开图片,并使用ImageTk.PhotoImage()函数将其转换为可在tkinter中使用的格式。修改你的代码如下:
- from tkinter import *
- from PIL import Image, ImageTk
- import os
- root = Tk()
- text = Text(root, width=30, height=30)
- text.pack()
- text.insert(INSERT, "快点击这里啊<click>")
- text.tag_add("come here", 1.7, 1.12)
- text.tag_config("come here", foreground="blue", underline=True)
- def enter(event):
- text.config(cursor="arrow")
- def leave(event):
- text.config(cursor="xterm")
- def click(event):
- os.chdir("C:\\users\\david\\Desktop")
- image = Image.open("qq.gif")
- photo = ImageTk.PhotoImage(image)
- text.image_create(END, image=photo)
- text.tag_bind("come here", "<Enter>", enter)
- text.tag_bind("come here", "<Leave>", leave)
- text.tag_bind("come here", "<Button-1>", click)
- mainloop()
复制代码
通过这种方式,你就可以成功加载并显示GIF图片了。 |
|