鱼C论坛

 找回密码
 立即注册
查看: 2070|回复: 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的图片吗?

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://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:

  1. pip install pillow
复制代码


安装完成后,你需要将导入语句改为:

  1. from PIL import Image, ImageTk
复制代码


然后,你可以使用PIL库中的Image.open()函数来打开图片,并使用ImageTk.PhotoImage()函数将其转换为可在tkinter中使用的格式。修改你的代码如下:

  1. from tkinter import *
  2. from PIL import Image, ImageTk
  3. import os

  4. root = Tk()
  5. text = Text(root, width=30, height=30)
  6. text.pack()
  7. text.insert(INSERT, "快点击这里啊<click>")
  8. text.tag_add("come here", 1.7, 1.12)
  9. text.tag_config("come here", foreground="blue", underline=True)

  10. def enter(event):
  11.     text.config(cursor="arrow")

  12. def leave(event):
  13.     text.config(cursor="xterm")

  14. def click(event):
  15.     os.chdir("C:\\users\\david\\Desktop")
  16.     image = Image.open("qq.gif")
  17.     photo = ImageTk.PhotoImage(image)
  18.     text.image_create(END, image=photo)

  19. text.tag_bind("come here", "<Enter>", enter)
  20. text.tag_bind("come here", "<Leave>", leave)
  21. text.tag_bind("come here", "<Button-1>", click)

  22. mainloop()
复制代码


通过这种方式,你就可以成功加载并显示GIF图片了。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-23 04:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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