python - Tkinter - 如何将文本更改为图像?

标签 python image tkinter text python-imaging-library

让我们以此作为示例程序:

from tkinter import *
import random
win = Tk()
win.geometry('200x200')

alphabets = ["A", "B", "C"]
rand_alpha = random.choice(alphabets)

lbl = Label(win, font = 'Ariel 30',text = rand_alpha)
lbl.pack()

win.mainloop()

在上面的程序中,我想将“rand_alpha”的文本更改为图像文件,以便我可以使用 PIL 来修改它。用python可以吗?

最佳答案

您可以使用ImageDraw来创建您想要的图像:

from tkinter import *
import random
from PIL import Image, ImageTk, ImageDraw, ImageFont

win = Tk()
win.geometry('200x200')

alphabets = ["A", "B", "C"]
rand_alpha = random.choice(alphabets)

image = Image.new('RGB', (200, 200), (255, 255, 255))  # adjust the size to what you want
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('arial.ttf', size=128) # adjust the font and size to what you want
w, h = draw.textsize(rand_alpha, font=font)
draw.text(((200-w)//2, (200-h)//2), font=font, text=rand_alpha, fill='black')
tkimage = ImageTk.PhotoImage(image)

lbl = Label(win, image=tkimage)
lbl.pack()

win.mainloop()

引用ImageDraw有关如何使用它的文档。

关于python - Tkinter - 如何将文本更改为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63280719/

相关文章:

python - 通过 Pythons 子进程使用换行符和 Linux 邮件命令发送邮件

python - 使用 LSTM 对使用 Keras 的可变长度信号进行多标签分类

python - 如何在python中通过网络发送实时视频

ios - 使用 AVCaptureSessionPreset 时如何更改图像质量

python - 多个按钮更改多个标签的颜色 TKINTER、PYTHON?

python - 使用 Tkinter 的 GUI 应用程序 - 拖放

python - Django Rest Framework ViewSet 出现 404 错误

jquery - 我如何在 html 中使用 jQuery css 将显示图像的视频放在图像前面?

Java文档图像缩放和旋转

Python - 将 Tkinter 图形添加到 PyQt 小部件