Bottom Page

Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 [Tkinter] Problem loading an image from directory into a Canvas object
#1
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?
Quote
#2
can you supply mundo.bmp
Quote
#3
Sure, here it is: https://drive.google.com/open?id=1i1AQoY...NrXI51n_dw
Quote
#4
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.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  [Tkinter] Display Selected Image from Directory and Resize it EchoLi 0 142 Oct-02-2019, 06:54 PM
Last Post: EchoLi
  [Tkinter] Resizing image inside Canvas (with Canvas' resize) Gupi 2 3,025 Jun-04-2019, 05:05 AM
Last Post: Gupi
  Canvas refreshing problem Faruk 2 488 Dec-04-2018, 08:52 AM
Last Post: Faruk
  'list' object has no attribute 'plot' problem BaartCM 2 4,615 Feb-03-2018, 09:20 PM
Last Post: BaartCM
  Problem with pygame not switching the mouse image Mondaythe1st 6 2,246 Jul-26-2017, 10:53 PM
Last Post: metulburr
  Drag and drop image object vijaysagi 1 7,085 Apr-06-2017, 09:36 AM
Last Post: wuf

Forum Jump:


Users browsing this thread: 1 Guest(s)