繁体   English   中英

Tkinter标签中的图像?

[英]Image in Tkinter Label?

我是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()

出于调试目的,请尝试避免使用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()
       img = Image.open('image_name')
       self.tkimage = ImageTk.PhotoImage(img)
       Label(self,image = self.tkimage).place(x=0, y=0, relwidth=1, relheight=1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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