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