Python - Problema con imagenes y tkinter

 
Vista:

Problema con imagenes y tkinter

Publicado por Víctor (9 intervenciones) el 13/11/2019 20:18:06
Hola:

Me ha ocurrido la siguiente cosa que me ha dejado un poco perplejo. Lo que quiero hacer es crear un gráfico con matplotlib y luego mostrarlo en una ventana tkinter; para lo que primero creo el gráfico, guardo en un fichero temporal y después lo leo con PIL, pero no funciona.

Tengo el siguiente código:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: UTF-8 -*-
 
import tkinter
import matplotlib.pyplot as mpl
 
import Carpeta_widgets.Modulo_widgets_formularios as MWF
 
datos = [1,2,4,6,5,3]
mpl.plot(datos)
mpl.savefig("Figuras/tmp001.png")
 
ventana = tkinter.Tk()
 
mwf = MWF.WidgetsFormularios()
mwf.icono(ventana,
          fila=1,
          file="Figuras/tmp001.png",
          width=300)
 
ventana.mainloop()

El método "icono" de la clase "WidgetsFormularios" es:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def icono(self,ventana,
              fila=0,columna=0,colExpand=1,filExpand=1,
              file="",texto="Imagen",
              width=70):
        """
            Crea una imagen con una etiqueta.
        - Version 1 VRM 2019-11-02 Inicial
        """
        try:
            imagePIL = Image.open(file)
        except:
            return tkinter.Label(ventana,text=texto)
        else:
            # Obtiene el tamaño
            anchura,altura = imagePIL.size
            relacion = anchura/altura
            imageRS = imagePIL.resize((width,int(width/relacion)),
                                      Image.ANTIALIAS)
            image = ImageTk.PhotoImage(imageRS)
            widget = tkinter.Label(ventana, image=image)
            widget.image = image # Para que no se pierda la referencia.
            widget.grid(row=fila,column=columna,
                        columnspan=colExpand,rowspan=filExpand)
            return widget

Este método presenta en una ventana la imagen que contiene el fichero "file", ajustando tamaño, etc...

Si ejecuto el primer script me sale el siguiente error:
1
2
3
4
5
6
7
8
9
10
11
Traceback (most recent call last):
  File "C:\Users\lenovo\Documents\Oropendola\ACS\codigo\Test_manual_estadisticas.py", line 18, in <module>
    width=300)
  File "C:\Users\lenovo\Documents\Oropendola\ACS\codigo\Carpeta_widgets\Modulo_widgets_formularios.py", line 79, in icono
    widget = tkinter.Label(ventana, image=image)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 2766, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 2299, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage10" doesn't exist

Pero si después de la linea 10 del script coloco mpl.show() no da error, pero me muestra dos veces el gráfico.

Gracias de antemano.-

RESUELTO:

Sólo hay que poner mpl.close() después de la linea 10. Quedaría el código del script:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding: UTF-8 -*-
 
import tkinter
import matplotlib.pyplot as mpl
 
import Carpeta_widgets.Modulo_widgets_formularios as MWF
 
datos = [1,2,4,6,5,30]
mpl.plot(datos)
mpl.savefig("Figuras/tmp001.png")
mpl.close()
 
ventana = tkinter.Tk()
 
mwf = MWF.WidgetsFormularios()
mwf.icono(ventana,
          fila=1,
          file="Figuras/tmp001.png",
          width=300)
 
ventana.mainloop()

Dejo el mensaje por si alguien tiene el mismo problema para que no pierda tanto tiempo como yo.

Disculpen la longitud del mensaje.-
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
1
Responder