我试图创建并显示一个空白图像,以便稍后进行编辑和更新。当不使用tkinter时,仅在图像显示时,此代码有效。当我运行以下代码时:
from random import randint
from time import *
from PIL import Image as Img
from PIL import ImageTk as ImgTk
from tkinter import *
main = Tk()
main.geometry('1001x1001')
width, height = map(int, input('width and height\n').split())
canvas = Canvas(main, width = width, height = height)
canvas.pack()
next_cells = []
img = Img.new('RGB', (width, height))
pix = img.load()
tkpix = ImgTk.PhotoImage(pix)
imgsprite = canvas.create_image(width,height,image=pix)
main.mainloop()
我收到以下错误:
File "/Applications/eeie", line 14, in <module>
tkpix = ImgTk.PhotoImage(pix)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PIL/ImageTk.py", line 108, in __init__
mode = Image.getmodebase(mode)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PIL/Image.py", line 275, in getmodebase
return ImageMode.getmode(mode).basemode
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PIL/ImageMode.py", line 64, in getmode
return _modes[mode]
builtins.KeyError: <PixelAccess object at 0x108aa4790>
是什么原因导致此错误?
答案 0 :(得分:1)
在这里,用代码描述。
from tkinter import *
import Image, ImageTk
# create canvas
canvas = Canvas(width=300, height=200, bg='black')
canvas.pack()
# create image object
img = Image.new('RGB', (60, 30), color='red')
new_image = ImageTk.PhotoImage(img)
# load into canvas
canvas.create_image(50, 10, image=new_image, anchor=NW)
mainloop()
输出:
要更新canvas创建功能,并在对对象进行更改后更新根。
from tkinter import *
import Image, ImageTk
import time
def update_position():
while True:
canvas.move(rectangle, 30, 10)
time.sleep(1)
root.update()
root = Tk()
# create canvas
canvas = Canvas(root, width=300, height=200, bg='black')
canvas.pack()
# create image object
img = Image.new('RGB', (60, 30), color='red')
new_image = ImageTk.PhotoImage(img)
# load into canvas
rectangle = canvas.create_image(50, 10, image=new_image, anchor=NW)
update_position()
root.mainloop()