Andrea Diaz
Andrea Diaz

Reputation: 1188

Create a text over an image using 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?

Upvotes: 4

Views: 15361

Answers (1)

probat
probat

Reputation: 1532

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()

Upvotes: 8

Related Questions