Python Forum
[Tkinter] Problem loading an image from directory into a Canvas object - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/Forum-Python-Coding)
+--- Forum: GUI (https://python-forum.io/Forum-GUI)
+--- Thread: [Tkinter] Problem loading an image from directory into a Canvas object (/Thread-Tkinter-Problem-loading-an-image-from-directory-into-a-Canvas-object)



Problem loading an image from directory into a Canvas object - tiotony - Sep-01-2018

Hi, everyone!

I'm having problems when trying to load a bmp image into a Canvas object using tkinter and what is driving me mad is that I don't even get an error message Huh .

This is my code:

import sys
import PIL
from PIL import Image, ImageTk
import argparse
import datetime
import cv2
import os
import imutils
import numpy as np
import pandas as pd
from tkinter import messagebox

import matplotlib.pyplot as plt

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.pagesizes import landscape
from reportlab.platypus import Image

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True

import reporte_support

class Reporte:
    def __init__(self, top=None, output_path = "./"):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85' 
        _ana2color = '#d9d9d9' # X11 color: 'gray85' 

        top.geometry("600x350+457+114")
        top.title("Reporte")
        top.configure(background="#99d9ea")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")

        self.output_path = output_path  # store output path
        self.DNI = ""
        self.muestra = ""
        
        self.abrir_datos()
        
        self.Labelframe1 = LabelFrame(top)
        self.Labelframe1.place(relx=0.52, rely=0.06, relheight=0.79
                , relwidth=0.43)
        self.Labelframe1.configure(relief=GROOVE)
        self.Labelframe1.configure(foreground="black")
        self.Labelframe1.configure(text='''Imagen de detección''')
        self.Labelframe1.configure(background="#fffa95")
        self.Labelframe1.configure(highlightbackground="#d9d9d9")
        self.Labelframe1.configure(highlightcolor="black")
        self.Labelframe1.configure(width=260)
        
        self.Canvas1 = Canvas(self.Labelframe1)
        self.Canvas1.place(relx=0.04, rely=0.08, relheight=0.88, relwidth=0.92
                , y=-12, h=6)
        self.Canvas1.configure(background="#000000")
        self.Canvas1.configure(borderwidth="2")
        self.Canvas1.configure(insertbackground="black")
        self.Canvas1.configure(relief=RIDGE)
        self.Canvas1.configure(selectbackground="#c4c4c4")
        self.Canvas1.configure(selectforeground="black")
        self.Canvas1.configure(width=243)

        self.Label1 = Label(top)
        self.Label1.place(relx=0.6, rely=0.89, height=21, width=118)
        self.Label1.configure(activebackground="#f9f9f9")
        self.Label1.configure(activeforeground="black")
        self.Label1.configure(background="#fffa95")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(highlightbackground="#d9d9d9")
        self.Label1.configure(highlightcolor="black")
        self.Label1.configure(text='''Muestra c/s parásitos''')

        self.Button1 = Button(top)
        self.Button1.place(relx=0.18, rely=0.89, height=24, width=98)
        self.Button1.configure(activebackground="#d9d9d9")
        self.Button1.configure(activeforeground="#000000")
        self.Button1.configure(background="#ffaa71")
        self.Button1.configure(disabledforeground="#a3a3a3")
        self.Button1.configure(foreground="#880015")
        self.Button1.configure(highlightbackground="#d9d9d9")
        self.Button1.configure(highlightcolor="black")
        self.Button1.configure(pady="0")
        self.Button1.configure(text='''Imprimir reporte''')
        
        self.Button1.configure(command=self.gen_reporte)

        self.Labelframe2 = LabelFrame(top)
        self.Labelframe2.place(relx=0.05, rely=0.06, relheight=0.79
                , relwidth=0.43)
        self.Labelframe2.configure(relief=GROOVE)
        self.Labelframe2.configure(foreground="black")
        self.Labelframe2.configure(text='''Datos''')
        self.Labelframe2.configure(background="#fffa95")
        self.Labelframe2.configure(highlightbackground="#d9d9d9")
        self.Labelframe2.configure(highlightcolor="black")
        self.Labelframe2.configure(width=260)

        self.Message1 = Message(self.Labelframe2)
        self.Message1.place(relx=0.04, rely=0.04, relheight=0.89, relwidth=0.89
                , y=-12, h=6)
        self.Message1.configure(background="#fffa95")
        self.Message1.configure(foreground="#000000")
        self.Message1.configure(highlightbackground="#d9d9d9")
        self.Message1.configure(highlightcolor="black")
        
        #########################
        self.db_paciente = pd.read_excel(os.path.join(self.output_path, self.DNI + '/' + 'datos.xlsx'))
        #########################
        self.Message1.configure(text="Nombre:\n\t\t" + self.db_paciente.at[0, 'Nombre'] +
                                "\nDNI:\n\t\t" + self.DNI +
                                "\nEdad:\n\t\t" + str(self.db_paciente.at[0, 'Edad']) +
                                "\nSexo:\n\t\t" + self.db_paciente.at[0, 'Sexo'] +
                                "\nN° de muestra:\n\t\t" + self.muestra +
                                "\nN° de historia clínica:\n\t\t" + self.db_paciente.at[0, 'Historia Clínica'])
        self.Message1.configure(width=200)
        
        ###########THIS IS THE LOADING IMAGE CODE##############
        print("antes de cargar imagen")
        image = PIL.Image.open("D:\\mundo.bmp")
        photo = PIL.ImageTk.PhotoImage(image, master = self.Canvas1)
        self.Canvas1.create_image(0,0,anchor='nw',image=photo)
        self.Canvas1.pack()
        print("carga imagen")
        #######################################################
        
        print("El DNI actual es " + self.DNI + " y la muestra actual es " + self.muestra + ".")
        
        self.dir_mues = os.path.join(self.output_path, self.DNI + '/' + self.muestra)
        
        print("self.dir_mues es: " + self.dir_mues)
        
    def gen_reporte(self):
        c = canvas.Canvas(self.dir_mues + '/' + "resultados.pdf", pagesize = landscape(letter))
        
        ###########THIS IS THE LOADING IMAGE CODE##############
        print("antes de cargar imagen")
        image = PIL.Image.open("D:\\mundo.bmp")
        photo = PIL.ImageTk.PhotoImage(image, master = self.Canvas1)
        self.Canvas1.create_image(0,0,anchor='nw',image=photo)
        self.Canvas1.pack()
        print("carga imagen")
        #######################################################

        
        #Formato
        c.setFont('Helvetica-Bold', 30, leading=None)
        c.drawCentredString(415, 550, "REPORTE DE RESULTADOS")
        c.setFont('Helvetica', 20, leading=None)

        c.drawAlignedString(415, 500, "Nombre     :     ")
        c.drawString(415, 500, self.db_paciente.at[0, 'Nombre'])
        
        c.drawAlignedString(415, 450, "DNI     :     ")
        c.drawString(415, 450, self.DNI)
        
        c.drawAlignedString(415, 400, "Edad     :     ")
        c.drawString(415, 400, str(self.db_paciente.at[0, 'Edad']))
        
        c.drawAlignedString(415, 350, "Sexo     :     ")
        c.drawString(415, 350, self.db_paciente.at[0, 'Sexo'])
        
        c.drawAlignedString(415, 300, "N° de muestra     :     ")
        c.drawString(415, 300, self.muestra)
        
        c.drawAlignedString(415, 250, "Resultado     :     ")
        c.drawString(415, 250, "Muestra c/s parásitos.")
        
        c.drawAlignedString(415, 200, "Historia Clínica     :     ")
        c.drawString(415, 200, str(self.db_paciente.at[0, 'Historia Clínica']))
        
        pic = "circulos.jpg"
        c.drawImage(pic, 300, 50, width=200, height=150)
        c.showPage()
        c.save()
        print("Reporte generado.")

    def abrir_datos(self):
        DNI_actual_txt = "current.txt"
        muestra_actual_txt = "muestra.txt"
        DNI_actual = os.path.join(self.output_path, DNI_actual_txt)
        muestra_actual = os.path.join(self.output_path, muestra_actual_txt)
        with open(DNI_actual, 'r+') as file:
            self.DNI = file.read()
            file.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
            file.close()
        with open(muestra_actual, 'r+') as file:
            self.muestra = file.read()
            file.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
            file.close()

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = Tk()
    top = Reporte (root)
    reporte_support.init(root, top)
    root.mainloop()

w = None
def create_Reporte(root, *args, **kwargs):
    '''Starting point when module is imported by another program.'''
    global w, w_win, rt
    rt = root
    w = Toplevel (root)
    top = Reporte (w)
    reporte_support.init(w, top, *args, **kwargs)
    return (w, top)

def destroy_Reporte():
    global w
    w.destroy()
    w = None

if __name__ == '__main__':
    vp_start_gui()
Could somebody, please, tell me what I am doing wrong?


RE: Problem loading an image from directory into a Canvas object - Larz60+ - Sep-01-2018

can you supply mundo.bmp


RE: Problem loading an image from directory into a Canvas object - tiotony - Sep-01-2018

Sure, here it is: https://drive.google.com/open?id=1i1AQoY8ownSN6d893vMPZsNrXI51n_dw


RE: Problem loading an image from directory into a Canvas object - woooee - Sep-02-2018

Quote:what is driving me mad is that I don't even get an error message
There is no error to report. You have to keep a copy of the image, otherwise it is garbage collected when the function, init in this case, exits, so does not show because it's gone. Make the photo variable an instance object.