Cómo actualizar la imagen de un widget Tkinter etiqueta?
-
28-09-2019 - |
Pregunta
Me gustaría ser capaz de cambiar a cabo una imagen en una etiqueta Tkinter, pero no estoy seguro de cómo hacerlo, excepto que se reemplazó el widget en sí.
Actualmente, puede mostrar una imagen de este modo:
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")
root.mainloop()
Sin embargo, cuando los accesos de los usuarios, dicen que la clave ENTER
, me gustaría cambiar la imagen.
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):
# change image
root.bind("<Return>", callback)
root.mainloop()
¿Es esto posible?
Solución
El label.configure
método funciona en panel.configure(image=img)
.
Lo que se olvidó de hacer era incluir la panel.image=img
, para evitar la recolección de basura de borrar la imagen.
La siguiente es la nueva versión:
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()
El código original funciona porque la imagen se almacena en la variable global img
.
Otros consejos
Otra opción para hacerlo.
El uso de la programación orientada a objetos y con una interfaz interactiva para actualizar la imagen.
from Tkinter import *
import tkFileDialog
from tkFileDialog import askdirectory
from PIL import Image
class GUI(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
w,h = 650, 650
master.minsize(width=w, height=h)
master.maxsize(width=w, height=h)
self.pack()
self.file = Button(self, text='Browse', command=self.choose)
self.choose = Label(self, text="Choose file").pack()
self.image = PhotoImage(file='cualitativa.gif')
self.label = Label(image=self.image)
self.file.pack()
self.label.pack()
def choose(self):
ifile = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
path = ifile.name
self.image2 = PhotoImage(file=path)
self.label.configure(image=self.image2)
self.label.image=self.image2
root = Tk()
app = GUI(master=root)
app.mainloop()
root.destroy()
Reemplazar 'cualitativa.jpg' la imagen predeterminada que desea utilizar para.