簡體   English   中英

嘗試在 tkinter 畫布中顯示圖像時出錯

[英]Error when trying to display image in tkinter canvas

我試圖創建並顯示一個空圖像,以便稍后進行編輯和更新。 此代碼在不使用 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>

是什么導致了這個錯誤?

給你,代碼中的描述。

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()

輸出:

在此處輸入圖片說明

更新畫布創建功能,並在更改對象后更新根。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM