Image
Chema Cortes
py en ch3m4.org
Lun Jun 19 12:59:35 CEST 2006
waldorf escribió:
> Hola. ¿Podeis indicarme que es incorrecto en el código siguiente?
>
> from Tkinter import *
> from PIL import Image,ImageTk
>
> def prueba():
> img=Image.open('image.jpg') # linea A
> imagen=ImageTk.PhotoImage(img) # linea B
> canvas.create_image(100,100,image=imagen) # linea C
>
> root=Tk()
> canvas=Canvas(root,height=400,width=400,bg='white')
> canvas.pack()
> boton=Button(root,command=prueba)
> boton.pack()
> root.mainloop()
>
> Notas:
> image.jpg está en el directorio por defecto.
>
> Si después de la línea C y dentro de la función prueba añado una nueva
> línea
> con algo que produzca error, la imagen se muestra al pulsar el botón, en
> caso contrario no.
>
> Si las líneas A y B las pongo en el programa principal también se
> muestra la
> imagen al pulsar el botón sin necesidad de añadir ninguna nueva línea a la
> función.
En la documentación del Canvas de Tkinter te dice:
"The image object. This should be a PhotoImage or BitmapImage, or a
compatible object (such as the PIL PhotoImage). The application must
keep a reference to the image object."
Debes mantener una "referencia" a la imagen. Pasa "imagen" a variable
global o, mejor aún, emplea orientación a objetos:
import Tkinter as tk
from PIL import Image,ImageTk
class App(tk.Frame):
def __init__(self,fichero):
tk.Frame.__init__(self)
self.canvas=tk.Canvas(self,height=400,width=400,bg='white')
self.canvas.pack()
self.boton=tk.Button(self,text="Carga imagen",command=self.prueba)
self.boton.pack()
self.fichero=fichero
def prueba(self):
img=Image.open(self.fichero)
self.imagen=ImageTk.PhotoImage(img)
self.canvas.create_image(100,100,image=self.imagen)
app=App('mifichero.jpg')
app.mainloop()
--
Chema Cortés (py en ch3m4.org)
"Proudly made on earth by generic humanoid carbon units"
Más información sobre la lista de distribución Python-es