2013-04-02 48 views
5

我想在圖像上顯示文字,但我無法做到這一點,任何人都可以幫忙。我無法在tkinter圖像上顯示文字

代碼:

# 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 

回答

7

標籤構造需要一個參數compound。將構造函數傳遞給圖像和文本,並傳遞compound作爲Tkinter.CENTER以將文本重疊到圖像上。此功能的文檔是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 

另請注意,你不應該混合包和網格。你應該選擇一個或另一個。參考:http://effbot.org/tkinterbook/grid.htm

P.S.以防萬一你的意思是要讓文本垂直高於圖像,可以使用與上面相同的代碼,除了設置爲compound=Tkinter.BOTTOM