简体   繁体   中英

How to change image in a Label in python using tkinter?

I have an image in a label and I want that image to be changed when I press the button but instead of changing the image the window becomes blank:

from tkinter import *
from PIL import Image,ImageTk
import os
root = Tk()
root.state("zoomed")
def chng():
    photo2 = ImageTk.PhotoImage(Image.open("upload.jpg"))
    img.config(image = photo2) 
    img.grid() 
photo = ImageTk.PhotoImage(Image.open("cat.jpg"))
img = Label(root,image = photo)
upload = Button(root, text= "Upload" ,height = 3, width = 12, command = 
chng)
upload.grid( )
for col_num in range(root.grid_size()[1]):
    root.columnconfigure(col_num, minsize=600)
for row_num in range(root.grid_size()[1]):
    root.rowconfigure(row_num, minsize=60)
img.grid() 
root.mainloop()

You have to keep a reference to the image.

def chng():
    photo2 = ImageTk.PhotoImage(Image.open("upload.jpg"))
    img.config(image = photo2) 
    img.photo_ref = photo2 # keep a reference

And you don't need the extra grid() call.

Try this:

def chng():
    photo2 = ImageTk.PhotoImage(Image.open("upload.jpg"))
    img.config(image = photo2) 
    img.grid()
    root.update_idletasks()
import Tkinter as tk
from PIL import Image

class Application(tk.Frame):
    def __init__(self, master=None):
    tk.Frame.__init__(self, master)
    self.grid(row=5,column=2)
    self.createWidgets()
    top = self.winfo_toplevel()
def createWidgets(self):
    self.grid()

app = Application()
simge = tk.PhotoImage(file="bg.png")
hira1 = tk.Label(image=simge)
hira1.grid(row=0,column=0,rowspan=5)

def manu1(event):
    simen1=tk.PhotoImage(file="bg1.png")
    hira1.configure(image=simen1)
    hira1(image=simen1)

hira1.bind("<Button 1>",manu1)
app.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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