猿问

尝试创建位图时:_tkinter.TclError:位图“pyimage2”未定义

有一个图像我想用不同的颜色绘制,所以我将它转换为位图,但是当我尝试在画布上创建它时出现错误。


这是代码:


import PIL.Image

from PIL import ImageTk

from tkinter import *



im = PIL.Image.open("lightbulb.gif")

small_im = im.resize((20,20), resample=PIL.Image.NEAREST).convert('1');


root = Tk()

canvas = Canvas(root,width=100,height=100,bg='black')

canvas.pack()

bitmap = ImageTk.BitmapImage(small_im)

bitmap_id = canvas.create_bitmap(3,3,background='', foreground='gray', bitmap=bitmap,

                                 anchor=NW)

root.mainloop()

我收到以下错误:


Traceback (most recent call last):

  File "/Users/ronen/Dropbox/trycanvas/bitmaps.py", line 13, in <module>

    bitmap_id = canvas.create_bitmap(3,3,background="", foreground="gray", bitmap=bitmap, anchor=NW)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 2486, in create_bitmap

    return self._create('bitmap', args, kw)

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 2480, in _create

    *(args + self._options(cnf, kw))))

_tkinter.TclError: bitmap "pyimage2" not defined

我究竟做错了什么?


蝴蝶不菲
浏览 311回答 2
2回答

HUWWW

好的,我现在明白是怎么回事了。ImageTk.BitmapImage实际上返回一个图像,而不是一个位图,但它可以用来改变颜色。因此,而不是:bitmap = ImageTk.BitmapImage(small_im)bitmap_id = canvas.create_bitmap(3,3,background='', foreground='gray', bitmap=bitmap,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;anchor=NW)我应该编码:from_bitmap = ImageTk.BitmapImage(small_im, background='', foreground='gray')bitmap_id = canvas.create_image(3,3, image=from_bitmap, anchor=NW)
随时随地看视频慕课网APP

相关分类

Python
我要回答