python怎么在画布上写字,在图像上插入文本,python

My project is about loading an image and when I click on a button, a text area appears in the image, and I can write a text on it and later on save the text written on the image and the image. To do so I used tkinter but I set my image as background and I added a text box(text widget) and enter a text, but obviously I can't save that image( the one set as background) and the text written on it. I tried using PIL but i didn't find what I was looking for.

This is my code using tkinter :

from tkinter import *

from PIL import ImageTk

import cv2

#root = Tk()

image=cv2.imread("New_refImg.png")

width_1, height_1,channels = image.shape

print(width_1)

print(height_1)

canvas = Canvas(width =height_1, height = width_1, bg = 'blue')

canvas.pack(expand = 1, fill = BOTH)

img = ImageTk.PhotoImage(file = "New_refImg.png")

canvas.create_image(0, 0, image = img, anchor = NW)

#Add text

entry = Entry(canvas, width=12)

entry.pack(side=BOTTOM,padx=43,pady=height_1-130) # "side" position button

def onok():

x= entry.get().split('x')

print(x)

Button(canvas, text='OK', command=onok).pack(side=LEFT)

mainloop()

解决方案

So, you could draw text into your canvas - Python: how to add text inside a canvas? - and then convert that canvas to an image for saving - How can I convert canvas content to an image?

However, I would instead recommend using PIL/Pillow. You can draw text onto an image - https://pillow.readthedocs.io/en/5.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text. You can provide the Pillow image to ImageTk.PhotoImage directly as an argument - ImageTk.PhotoImage(im). You can naturally save the image to a file - http://pillow.readthedocs.io/en/5.2.x/reference/Image.html#PIL.Image.Image.save

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值