简体   繁体   中英

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

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

PS 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM