Search code examples
python-3.xtkintertkinter-label

Change the image in the Label in Tkinter using a function


I am making a program GUI in Tkinter but I am stuck in this part.

from Tkinter import *
from PIL import Image, ImageTk

def add_imgage():
    player_label.destroy()
    player3_token = ImageTk.PhotoImage(Image.open('./gallery/Scissor_icon.jpg'))
    player_label = Label(vs_frame, image=player3_token, borderwidth=2, relief=GROOVE, width=50, height=50)

if __name__ == '__main__':
    root = Tk()

    SCREEN_HEIGHT = 500
    SCREEN_WIDTH = 800
    root.geometry(f"{SCREEN_WIDTH}x{SCREEN_HEIGHT}")
    root.title('test window')
    
    frame1 = Frame(root)
    frame1.pack(pady=30)

    player_label = Label(frame1, borderwidth=2, relief=GROOVE, width=10, height=5)
    player_label.pack(side=LEFT)

I want to add an image in the player_label through the add_image() function.


Solution

  • First; you have to run the function for it to create an image.

    Then; there is no need to destroy the label. You can configure it in place. You also have to save a reference to the image or it will be garbage collected when the function exits.

    I'm using Python3 so i changed the name Tkinter to tkinter, no first capital letter.

    from tkinter import *
    from PIL import Image, ImageTk
    
    def add_imgage():
        player3_token = ImageTk.PhotoImage(Image.open('images/jones.png'))
        player_label.config(image=player3_token, borderwidth=2, # Config the label
                             relief=GROOVE, width=50, height=50)
        player_label.image = player3_token  # Save reference to image
    
    if __name__ == '__main__':
        root = Tk()
    
        SCREEN_HEIGHT = 500
        SCREEN_WIDTH = 800
        root.geometry(f"{SCREEN_WIDTH}x{SCREEN_HEIGHT}")
        root.title('test window')
        
        frame1 = Frame(root)
        frame1.pack(pady=30)
    
        player_label = Label(frame1, borderwidth=2, relief=GROOVE,
                             width=10, height=5)
        player_label.pack(side=LEFT)
    
        add_imgage()    # Run the function to add image