How to Update the Image of a Tkinter Label Widget

How to update the image of a Tkinter Label widget?

The method label.configure does work in panel.configure(image=img).

What I forgot to do was include the panel.image=img, to prevent garbage collection from deleting the image.

The following is the new version:

import Tkinter as tk
import ImageTk

root = tk.Tk()

img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")

def callback(e):
img2 = ImageTk.PhotoImage(Image.open(path2))
panel.configure(image=img2)
panel.image = img2

root.bind("<Return>", callback)
root.mainloop()

The original code works because the image is stored in the global variable img.

How to dynamically update an image in a tkinter label widget?

The problem is that you are calling after(0, ...) which adds a job to the "after" queue to be run as soon as possible. However, your while loop runs extremely quickly and never gives the event loop the chance to process queued events, so the entire loop ends before a single image changes.

Once the event loop is able to process the events, tkinter will try to process all pending events that are past due. Since you used a timeout of zero, they will all be past due so tkinter will run them all as fast as possible.

The better solution is to have the function that updates the image also be responsible for scheduling the next update. For example:

def update_image(delay, count):
<your existing code here>

# schedule the next iteration, until the counter drops to zero
if count > 0:
slot1.after(delay, update_image, delay, count-1)

With that, you call it once and then it calls itself repeatedly after that:

update_image(100, 10)

How to refresh a image in tkinter

After you have updated the image file result_veg.jpeg inside get_call(), you need to reload it and assign to self.update_img:

def update_image(self, *args, **kwargs):
# reload the updated result_veg.jpeg
self.update_img = ImageTk.PhotoImage(file='result_veg.jpeg')
self.Preview_Image.itemconfig(self.image_id, image=self.update_img)

Image in label does not immideately change after function call

time.sleep() won't work here as it stops the execution of the program, you'll have to use after...and its also a bad practice to use sleep in GUI programming.

root.after(time_delay, function_to_run, args_of_fun_to_run)

So in your case it'll like

def change_image():
panel.configure(image = im3)
panel.image = im3

and in your callback function

def callback(e):
panel.configure(image = im2)
panel.image = im2
#after 2 seconds it'll call the above function
window.after(2000, change_image)


Related Topics



Leave a reply



Submit