Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a text over an image using python Tkinter

Tags:

python

tkinter

I am creating an Arduino interface on Sublime using python Tkinter..

I need to show a text over an image. Located in the middle of the screen (512, 200). I don't know how to do it using this library

import Tkinter as tk
from Tkinter import *
root = tk.Tk()
root.geometry("1024x574")
root.title("window")
photo = tk.PhotoImage(file= r"hi.gif")
cv = tk.Canvas()
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(0, 0, image=photo, anchor='nw')
text=['my text']
root.mainloop()

Any suggestions?

like image 733
Andrea Diaz Avatar asked Oct 20 '25 09:10

Andrea Diaz


1 Answers

You need to create a tk label widget and add your text to it. Then you need to use the tk label option compound=.

Taken directly from http://effbot.org/tkinterbook/label.htm:

"compound=
Controls how to combine text and image in the label. By default, if an image or bitmap is given, it is drawn instead of the text. If this option is set to CENTER, the text is drawn on top of the image. If this option is set to one of BOTTOM, LEFT, RIGHT, or TOP, the image is drawn besides the text (use BOTTOM to draw the image under the text, etc.). Default is NONE."

The following is a minimal but working example that accomplishes what you asked for:

import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()

image = Image.open('hi.gif')
tk_image = ImageTk.PhotoImage(image)

label = tk.Label(root, text='Some Plain Text', image=tk_image, compound='center')
label.pack()

root.mainloop()
like image 184
probat Avatar answered Oct 21 '25 21:10

probat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!