I can't display text over my tkinter image

13,697

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.

Share:
13,697
user2175282
Author by

user2175282

Updated on June 27, 2022

Comments

  • user2175282
    user2175282 almost 2 years

    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