8

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.

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()
user513951
  • 12,445
  • 7
  • 65
  • 82
Shivamshaz
  • 262
  • 2
  • 3
  • 10
  • 2
    Works fine for me. Is this your actual code? If not, my guess would be that the [image is garbage collected](http://stackoverflow.com/a/15435134/1639625). Do you get any error? – tobias_k Sep 02 '14 at 08:04
  • No there is no error, just an empty window. – Shivamshaz Sep 02 '14 at 09:41
  • As I said, works fine for me... so if this is your original code, could it be that your 'logo.png' in in fact much bigger and you are seeing just the top-left (white) corner of it? Also, what exact python version are you using? – tobias_k Sep 02 '14 at 10:37
  • 1
    Got it, logo.png was too large to be displayed. Thanks !! – Shivamshaz Sep 02 '14 at 11:27
  • 2
    You can use `Image.open('logo.png').resize((400,100))` to resize it. – tobias_k Sep 02 '14 at 11:39

2 Answers2

8

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.

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()
Artem
  • 135
  • 5
2
       img = Image.open('image_name')
       self.tkimage = ImageTk.PhotoImage(img)
       Label(self,image = self.tkimage).place(x=0, y=0, relwidth=1, relheight=1)
Jachdich
  • 782
  • 8
  • 23
  • 11
    Please explain what the code does, and how it fixes the OP's problem. Code-only answers without explanation are not useful to other readers, and therefore will likely attract downvotes. – Jesse Jun 12 '18 at 08:00