【问题标题】:I can't display text over my tkinter image我无法在我的 tkinter 图像上显示文本
【发布时间】:2013-03-24 08:35:49
【问题描述】:

我正在尝试在我的图像上显示文本,但我无法做到这一点,谁能帮忙。

代码:

# 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

【问题讨论】:

    标签: python image python-2.7 tkinter python-imaging-library


    【解决方案1】:

    Label 构造函数接受一个参数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

    附:万一你的意思是你想让文本垂直高于图像,你可以使用与上面相同的代码,除了设置compound=Tkinter.BOTTOM

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多