Python Tkinter 标签中的图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25617945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Image in Tkinter Label?
提问by Shivamshaz
I am new to python GUI programming, I want to add a image in my tkinter label, I have created the following code but the window is not showing my image. Path of image is the same folder as this code.
我是 python GUI 编程的新手,我想在我的 tkinter 标签中添加一个图像,我创建了以下代码但窗口没有显示我的图像。图像路径与此代码相同的文件夹。
import ImageTk
import Tkinter as tk
from Tkinter import *
from PIL import Image
def make_label(master, x, y, w, h, img, *args, **kwargs):
f = Frame(master, height = h, width = w)
f.pack_propagate(0)
f.place(x = x, y = y)
label = Label(f, image = img, *args, **kwargs)
label.pack(fill = BOTH, expand = 1)
return label
if __name__ == '__main__':
root = tk.Tk()
frame = tk.Frame(root, width=400, height=600, background='white')
frame.pack_propagate(0)
frame.pack()
img = ImageTk.PhotoImage(Image.open('logo.png'))
make_label(root, 0, 0, 400, 100, img)
root.mainloop()
回答by Artem
For debugging purpose try to avoid the use of PIL and load some *.gif (or another acceptable) file directly in PhotoImage, like shown below, if it'll work for you then just convert your image in *.gif or try to deal with PIL.
出于调试目的,尽量避免使用 PIL 并直接在 PhotoImage 中加载一些 *.gif(或其他可接受的)文件,如下所示,如果它适合您,那么只需将您的图像转换为 *.gif 或尝试处理与 PIL。
from tkinter import *
def make_label(parent, img):
label = Label(parent, image=img)
label.pack()
if __name__ == '__main__':
root = Tk()
frame = Frame(root, width=400, height=600, background='white')
frame.pack_propagate(0)
frame.pack()
img = PhotoImage(file='logo.gif')
make_label(frame, img)
root.mainloop()
回答by Sardorbek Muhtorov
img = Image.open('image_name')
self.tkimage = ImageTk.PhotoImage(img)
Label(self,image = self.tkimage).place(x=0, y=0, relwidth=1, relheight=1)

