python - 如何在 Tkinter on Canvas 中打开 PIL 图像

标签 python tkinter python-imaging-library tkinter-canvas

我似乎无法让我的 PIL 图像在 Canvas 上工作。代码:

from Tkinter import*
import Image, ImageTk
root = Tk()
root.geometry('1000x1000')
canvas = Canvas(root,width=999,height=999)
canvas.pack()
image = ImageTk.PhotoImage("ball.gif")
imagesprite = canvas.create_image(400,400,image=image)
root.mainloop()

错误:

Traceback (most recent call last):
  File "C:/Users/Mark Malkin/Desktop/3d Graphics Testing/afdds.py", line 7, in <module>
    image = ImageTk.PhotoImage("ball.gif")
  File "C:\Python27\lib\site-packages\PIL\ImageTk.py", line 109, in __init__
    mode = Image.getmodebase(mode)
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 245, in getmodebase
    return ImageMode.getmode(mode).basemode
  File "C:\Python27\lib\site-packages\PIL\ImageMode.py", line 50, in getmode
    return _modes[mode]
KeyError: 'ball.gif'

我需要使用 PIL 图像而不是 PhotoImages,因为我想调整图像的大小。请不要建议切换到 Pygame,因为我想使用 Tkinter。

最佳答案

首先尝试创建一个 PIL 图像,然后使用它来创建 PhotoImage。

from Tkinter import *
import Image, ImageTk
root = Tk()
root.geometry('1000x1000')
canvas = Canvas(root,width=999,height=999)
canvas.pack()
pilImage = Image.open("ball.gif")
image = ImageTk.PhotoImage(pilImage)
imagesprite = canvas.create_image(400,400,image=image)
root.mainloop()

关于python - 如何在 Tkinter on Canvas 中打开 PIL 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18369936/

相关文章:

python - 重新初始化 PLY 解析器

python - Django 信号未接收/工作

python通过按钮事件清除文本框

python - 使用 Python 在 Maya 中调整图像大小

python - 如何让 matplotlib 的 imshow 生成图像而不被绘制

python - 使用 Python 3.5 和 Anaconda 找不到模块 cPickle

python - Matplotlib colorbar - 更改了限制行为

Python 函数变量与类

python - ttk.Button 返回 None

Python Pillow 从像素制作 gif