代码之家  ›  专栏  ›  技术社区  ›  Armster

如何在tkinter中的图像上添加文本

  •  1
  • Armster  · 技术社区  · 7 年前

    我想知道如何在Tkinter中为图像添加文本。我输入以下代码:

    import PIL
    from PIL import ImageFont
    from PIL import Image
    from PIL import ImageDraw
    draw=ImageDraw.Draw("maybe.png")
    pixellat=ImageFont.truetype("pixellat.ttf",18)
    draw.text((125, 125),"This is a test",(255,255,255),font=pixellat)
    

    但我得到这个错误:

    Traceback (most recent call last):
    File "/usr/local/lib/python3.7/site- 
    packages/PIL/ImageDraw.py", line 344, in Draw
    return im.getdraw(mode)
    AttributeError: 'str' object has no attribute 'getdraw'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
    File "/Users/Apple/Desktop/pong 1.2/pong menu.py", line 41, in <module>
    draw=ImageDraw.Draw("maybe.png")
    File "/usr/local/lib/python3.7/site- 
    packages/PIL/ImageDraw.py", line 346, in Draw
    return ImageDraw(im, mode)
    File "/usr/local/lib/python3.7/site-packages/PIL/ImageDraw.py", line 60, in __init__
    im.load()
    AttributeError: 'str' object has no attribute 'load'
    

    你能帮我修一下吗?谢谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mark Setchell    7 年前

    您需要先打开/加载图像…像这样:

    <预先> <代码>!/USR/Local/bin/python3号 将numpy导入为np 从PIL导入图像、图像绘制、图像字体 #打开输入图像 im=image.open('image.png').convert('rgb') #获取绘图上下文 draw=imagedraw.draw(im) pixella=imagefont.truetype(“/library/fonts/apple chancery.ttf”,48) draw.text((80,40),“这是一个测试”,(255255255),字体=像素) 豁免 im.save('result.png') < /代码>

    enter image description here