python - 我无法在我的 tkinter 图像上显示文本

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

我想在我的图片上显示文字,但我做不到,有人能帮忙吗。

代码:

# 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

最佳答案

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

另请注意,您不应该混合使用 pack 和 grid。你应该选择其中之一。引用:http://effbot.org/tkinterbook/grid.htm

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

关于python - 我无法在我的 tkinter 图像上显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774459/

相关文章:

python - 在 Scrapy 蜘蛛中动态添加到 allowed_domains

python - 无法在 Mac OS El Capitan 上安装 nltk

python - 如何在读取大 csv 文件时解决 pandas 的内存问题

python - 如何在 python 中使用 Selenium 关闭浏览器弹出窗口?

python - 对于给定的长度,输入的组合或排列

html - 图像未占据带有动态文本的 div 旁边容器的全高

java - picasso 图书馆不显示来自 URL 的图像

python - 在python中使用PIL以相同的裁剪尺寸裁剪整个图像

python - String.maketrans 用于英语和波斯语数字

c - 如何使 Python 对象表现得像 numpy 数组?