如何在tkinter中的图像顶部添加文本 [英] How to add text on top of an image in tkinter

查看:218
本文介绍了如何在tkinter中的图像顶部添加文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在tkinter中的图像上添加文本.我输入以下代码:

I want to know how to add text on to of an image in tkinter. I type in the following code:

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'

您能帮我解决这个问题吗?谢谢.

Can you help me fix this? Thanks.

推荐答案

您需要先打开/加载图像,如下所示:

You need to open/load the image first... like this:

#!/usr/local/bin/python3

import numpy as np
from PIL import Image, ImageDraw, ImageFont

# Open input image
im = Image.open('image.png').convert('RGB')

# Get a drawing context
draw = ImageDraw.Draw(im)

pixellat=ImageFont.truetype("/Library/Fonts/Apple Chancery.ttf",48)
draw.text((80, 40),"This is a test",(255,255,255),font=pixellat)

# Save
im.save('result.png')

这篇关于如何在tkinter中的图像顶部添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆