python - 尝试创建位图 : _tkinter. TclError: 位图 "pyimage2"未定义时

标签 python python-3.x tkinter python-imaging-library

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

这是代码:

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

我做错了什么?

最佳答案

tkinter canvas.create_bitmap() 方法期望其 bitmap= 选项是一个包含名称的字符串 strong> 标准位图之一(分别是 'error''gray75''gray50''gray25' , 'gray12', '沙漏', 'info', 'questhead', 'question''warning'),如下所示:

image showing the standard bitmaps graphically

或者 包含您自己的文件的路径名,采用 .xbm 文件格式,前缀为 @ 字符。

下面是如何修改代码,以便将要显示的图像保存在临时 .xbm 格式文件中,然后告诉 tkinter 使用该文件:

import os
import PIL.Image
from PIL import ImageTk
from tempfile import NamedTemporaryFile
import tkinter as tk

im = PIL.Image.open("lightbulb.gif")
small_img = im.resize((20,20), resample=PIL.Image.NEAREST).convert('1');

with NamedTemporaryFile(suffix='.xbm', delete=False) as temp_img:
    small_img.save(temp_img.name)

root = tk.Tk()
canvas = tk.Canvas(root, width=100, height=100, bg='black')
canvas.pack()
bitmap_id = canvas.create_bitmap(3, 3, background='', foreground='gray',
                                 bitmap='@'+temp_img.name, anchor=tk.NW)
root.mainloop()

try:  # Cleanup
    os.remove(temp_img.name)  # Get rid of named temporary file.
except FileNotFoundError:
    pass

关于python - 尝试创建位图 : _tkinter. TclError: 位图 "pyimage2"未定义时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051101/

相关文章:

python 鳗鱼 : "Access Denied"

python - 基于条件循环将新行插入 Pandas DF

python - 具有特定数组条件的 while 循环

python-3.x - 如何在.kv文件中实现for循环

python - 如何在 Mac OS 上使用 Tkinter 获得黑色文件对话框?

python - Tkinter Canvas 设置为其容器的大小

python - 有没有办法在 Python 2.5 中模拟 Python 3 元类的 __prepare__ 特殊方法?

python - 我该如何修复这个Python登录系统代码?

python - 在 Tkinter Canvas 中创建 LabelFrame

python-3.x - Tkinter w.destroy() 阻止/重置窗口大小调整