use*_*814 8 python tkinter python-imaging-library tkinter-canvas
我似乎无法让我的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()
Run Code Online (Sandbox Code Playgroud)
错误:
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'
Run Code Online (Sandbox Code Playgroud)
我需要使用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()
Run Code Online (Sandbox Code Playgroud)
小智 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()
Run Code Online (Sandbox Code Playgroud)
(一个老问题,但到目前为止答案仅是一半。)
阅读文档:
class PIL.ImageTk.PhotoImage(image=None, size=None, **kw)
Run Code Online (Sandbox Code Playgroud)
image– PIL图像或模式字符串。[...]file–从中加载图像的文件名(使用Image.open(file))。因此,在您的示例中,使用
image = ImageTk.PhotoImage(file="ball.gif")
Run Code Online (Sandbox Code Playgroud)
或明确地
image = ImageTk.PhotoImage(Image("ball.gif"))
Run Code Online (Sandbox Code Playgroud)
(请记住-正确无误:请在Python程序中保留对图像对象的引用,否则在您看到它之前将对其进行垃圾收集。)
| 归档时间: |
|
| 查看次数: |
29120 次 |
| 最近记录: |