I am trying to display text on top of my image but I cannot do do this, can anyone help please.
Code:
# import Image and the graphics package Tkinter
import Tkinter
import Image, ImageTk
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
## def create_widgets(self):
# create welcome label
label1 = Tkinter.Label(self, text = "Update User")
label1.grid(row = 0, column = 1, columnspan = 2, sticky = 'W')
# open a SPIDER image and convert to byte format
im = Image.open('C:\Users\JOHN\Desktop\key.jpg')
root = Tkinter.Tk() # A root window for displaying objects
# Convert the Image object into a TkPhoto object
tkimage = ImageTk.PhotoImage(im)
Tkinter.Label(root, image=tkimage).pack() # Put it in the display window
root.mainloop() # Start the GUI
In order to add text inside a tkinter frame, we can use the create_text() method. We can define create_text() by adding values of font, text, and other options such as create_text(x,y,font, text, options….).
Tkinter relies on Pillow for working with images. Pillow is a fork of the Python Imaging Library, and can be imported in a Python console as PIL. Pillow has the following characteristics: Support for a wide range of image file formats, including PNG, JPEG and GIF.
Images can be shown with tkinter. Images can be in a variety of formats including jpeg images.
The Label constructor takes a parameter compound
. Pass the constructor both the image and text, and pass in compound
as Tkinter.CENTER
to overlap the text onto the image. Documentation for this feature is at http://effbot.org/tkinterbook/label.htm
import Tkinter
import Image, ImageTk
# open a SPIDER image and convert to byte format
im = Image.open(r'C:\Users\JOHN\Desktop\key.jpg')
root = Tkinter.Tk() # A root window for displaying objects
# Convert the Image object into a TkPhoto object
tkimage = ImageTk.PhotoImage(im)
Tkinter.Label(root, image=tkimage, text="Update User", compound=Tkinter.CENTER).pack() # Put it in the display window
root.mainloop() # Start the GUI
Also note, you're not supposed to mix pack and grid. You should choose one or the other. Reference: http://effbot.org/tkinterbook/grid.htm
P.S. just in case you meant you want the text to be vertically higher than the image, you can use the same code as above, except set compound=Tkinter.BOTTOM
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With