鱼C论坛

 找回密码
 立即注册
查看: 977|回复: 1

tkinter的图片问题

[复制链接]
发表于 2023-8-31 18:02:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
from tkinter import *
import urllib.request
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")
    photo = PhotoImage(file = "qq.gif")
    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()

路径是对的,但为什么会发生tkinter.TclError: couldn't recognize data in image file "qq.gif",不是说PhotoImage能认得出gif的图片吗?

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 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:
pip install pillow

安装完成后,你需要将导入语句改为:
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图片了。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-8 21:45

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表