Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't display text over my tkinter image

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
like image 727
user2175282 Avatar asked Apr 02 '13 21:04

user2175282


People also ask

How do you insert text in tkinter?

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….).

Does tkinter work with PNG?

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.

Can you use JPG in tkinter?

Images can be shown with tkinter. Images can be in a variety of formats including jpeg images.


1 Answers

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.

like image 149
twasbrillig Avatar answered Oct 21 '22 15:10

twasbrillig