9

我似乎无法让我的 PIL Image 在画布上工作。代码:

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,因为我想调整图像大小。请不要因为我想使用 Tkinter 而建议切换到 Pygame。

4

4 回答 4

17

尝试先创建一个 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()
于 2013-08-22T00:46:55.050 回答
8

(一个老问题,但到目前为止的答案只完成了一半。)

阅读文档:

class PIL.ImageTk.PhotoImage(image=None, size=None, **kw)
  • image– PIL 图像或模式字符串。[...]
  • file– 从中加载图像的文件名(使用Image.open(file))。

所以在你的例子中,使用

image = ImageTk.PhotoImage(file="ball.gif")

或明确

image = ImageTk.PhotoImage(Image("ball.gif"))

(记住——正如你做对的那样:在你的 Python 程序中保留对图像对象的引用,否则在你看到它之前它就被垃圾收集了。)

于 2017-03-06T14:25:05.473 回答
5

您可以导入多种图像格式,并使用此代码调整大小。“basewidth”设置图像的宽度。

from Tkinter import *
import PIL
from PIL import ImageTk, Image

root=Tk()
image = Image.open("/path/to/your/image.jpg")
canvas=Canvas(root, height=200, width=200)
basewidth = 150
wpercent = (basewidth / float(image.size[0]))
hsize = int((float(image.size[1]) * float(wpercent)))
image = image.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
photo = ImageTk.PhotoImage(image)
item4 = canvas.create_image(100, 80, image=photo)

canvas.pack(side = TOP, expand=True, fill=BOTH)
root.mainloop()
于 2013-10-18T13:26:33.393 回答
3

在这个问题上,我把头撞在墙上一段时间,直到我发现以下内容:

http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm

显然,Python 的垃圾收集器可以丢弃 ImageTk 对象。我想使用很多小部件(比如我的)的应用程序更容易受到这种行为的影响。

于 2019-04-13T00:12:56.677 回答