Python Forum
Tkinter: An image and label are not appearing.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tkinter: An image and label are not appearing.
#1
Hello,

I have this python code:

import tkinter as tk
from typing import Self
import selenium 
import os
import shutil
import getpass
import requests
import openpyxl
import easygui 


from tkinter import filedialog
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.edge.service import Service as EdgeService
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter
from alive_progress import alive_bar
import tqdm
from urllib3.util.retry import Retry
from icecream import ic
from colorama import Fore, Back, Style
from termcolor import colored, cprint
from datetime import datetime
from PIL import Image, ImageTk

#para borrar despues
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def read_column(excel_file):
    wb = openpyxl.load_workbook(excel_file)

    sheet = wb.active
    val_col_a = []

    for cell in sheet['A']:
        if cell.value is None:
            break
        else:
            val_col_a.append(cell.value)
    wb.close()

    file_path = filedialog.askdirectory(title="Please select the destination folder")
    if file_path:
        files_in_folder = os.listdir(file_path) #List all the files from the folder
        image3 = Image.open("Images/Download_Logo.png")
        resimage_download = image3.resize((27,30))
        image3 = ImageTk.PhotoImage(resimage_download)
        image_download = tk.Label(window, image=image3, borderwidth=0)
        image_download.place(x=62, y=240)
        
        download_text = tk.Label(window, text="Downloading the files", font=("Arial", 9, "bold"), bg="white")
        download_text.place(x=100, y=245)

    else:
        cprint("No destination folder was selected.\nTerminating program...", 'light_red')
        exit()
    return val_col_a, file_path

def move_files(tf, fp, df):
    for index_row, row in enumerate(tf):
        destiny = fp + "/" + tf[index_row][0]
        for index_col, col in enumerate(row[1:],start=1):
            source = df + "/" + tf[index_row][index_col]
            if not os.path.exists(destiny + "/" + tf[index_row][index_col]):
                    if os.path.exists(source):                               
                        shutil.move(source , destiny)


def goCheck(rpf, fp):
    ic("Process started at: ", current_time)
    
    transfiles = []
    options = webdriver.EdgeOptions()
    #options = webdriver.ChromeOptions()
    #options.add_experimental_option("detach", True)

    
    
    prefs = {
            "download.default_directory": "C:\\FO\\FO\\",  # Replace with your desired download directory
            "download.prompt_for_download": False,
            "download.directory_upgrade": True,
            "safebrowsing.enabled": False,
            "plugins.always_open_pdf_externally": True  # This option is specific to PDFs
            }
    driver = webdriver.Edge(service=EdgeService(), options=options)
    #driver = webdriver.Chrome(options=options)
    #edge_options.add_experimental_option("prefs", prefs)
    options.add_experimental_option("prefs", prefs)
    driver.get('https://ezv.bz.com/')
    #webPage = requests.get('https://ezv.bz.com/FO_Attachments.cfm?ViewType=2')
    driver.switch_to.window(driver.window_handles[-1])
    driver.maximize_window()
    sleep(20)
    driver.switch_to.frame('topFrame')
    
    #driver.find_element(By.XPATH, "//input[@name='DocNumber']").send_keys(rpf[0])
    with alive_bar(len(rpf), title=f'{blue}Accesing eZV and Downloading the attachments ->{reset}') as bar:
        for j in range(len(rpf)):
            sleep(0.1)
            driver.switch_to.parent_frame()
            driver.switch_to.parent_frame()
            driver.switch_to.frame(0)
            driver.find_element(By.XPATH, "//input[@name='DocNumber']").click()
            driver.find_element(By.XPATH, "//input[@name='DocNumber']").clear()
            driver.find_element(By.XPATH, "//input[@name='DocNumber']").send_keys(rpf[j])
            driver.find_element(By.XPATH, "//input[@name='Search']").click()
            sleep(10)
            #driver.find_element(By.XPATH, "//input[@name='Search']").click()
            driver.switch_to.parent_frame()
            driver.switch_to.frame(1)
            driver.switch_to.frame(1)
            if driver.find_element(By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/form[1]/table[1]/tbody[1]/tr[2]/td[1]/table[1]").text == "  No Records Found. Click the 'Load Archive Data' button below to search older documents.  ":
                ic("Processing Invoice: "+rpf[j])
                bar()
                continue
            else:
                #print(driver.find_element(By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/form[1]/table[1]/tbody[1]/tr[2]/td[1]/table[1]").text)
                #ic(driver.find_element(By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/form[1]/table[1]/tbody[1]/tr[2]/td[1]/table[1]").text)
                ic("Processing Invoice: "+rpf[j])
                driver.find_element(By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/form[1]/table[1]/tbody[1]/tr[3]/td[3]/a[1]").click()
                
                driver.switch_to.parent_frame()
                driver.switch_to.frame(0)
                
                #Clicks on Attachment tab
                driver.find_element(By.XPATH, "/html[1]/body[1]/table[1]/tbody[1]/tr[2]/td[2]/table[1]/tbody[1]/tr[1]/td[3]").click()
                driver.switch_to.parent_frame()
                driver.switch_to.frame(1)
                
                #Go through the table and download all the files
                #original_window_handle = driver.current_window_handle
                table_id = '/html[1]/body[1]/div[1]/div[1]/div[1]/table[1]' #"//body/div[@id='contents']/div[@id='main']/div/table[1]"
                table = driver.find_element(By.XPATH, table_id)
                body = table.find_element(By.TAG_NAME, 'tbody')
                rows = table.find_elements(By.TAG_NAME, "tr")

                k = 0
                i = 0
                
                
                main_window = driver.window_handles[0]

                #EXTRACT THE INFORMATION OF THE TABLE TO LATER BE TRANSFERRED TO A FOLDER
                column_index = 2
                column_values = []
                row_data = []
                folder_2_create = fp + "/" + rpf[j]
                column_values.append(rpf[j])
                os.makedirs(folder_2_create, exist_ok=True)
                
                
                input_elements = driver.find_elements(By.CSS_SELECTOR, 'input[name="FileName"]')
                for input_element in input_elements:
                    input_value = input_element.get_attribute('value')
                    if ".xml" in input_value or ".msg" in input_value:
                        continue
                    else:
                        column_values.append(input_value)
                        #ic(input_value)
                transfiles.append(column_values)
                #ic(transfiles)        

                #DOWNLOAD ALL THE FILES FROM THE LINKS AT ONCE
                driver.execute_script('''
                    var buttons = document.querySelectorAll(".download");
                    for (var i = 0; i < buttons.length; i++){
                        buttons[i].click();
                    }
                                        ''')
                
                #EXTRACT THE INFORMATION OF THE TABLE TO LATER BE TRANSFERRED TO A FOLDER
                #LOOK FOR INVOICEBULKERV4.PY FOR THIS PART
                
                #================================================================
                sleep(17)
                driver.quit()
                #options = webdriver.ChromeOptions()
                options = webdriver.EdgeOptions()
            #options.add_experimental_option("detach", True)

            
            
                prefs = {
                        "download.default_directory": "C:\\FO\\FO\\",  # Replace with your desired download directory
                        "download.prompt_for_download": False,
                        "download.directory_upgrade": True,
                        "safebrowsing.enabled": False,
                        "plugins.always_open_pdf_externally": True  # This option is specific to PDFs
                        }
                driver = webdriver.Edge(options=options)
                #edge_options.add_experimental_option("prefs", prefs)
                options.add_experimental_option("prefs", prefs)
                driver.get('https://ezv.bz.com/')
                #webPage = requests.get('https://ezv.bz.com/FO_Attachments.cfm?ViewType=2')
                driver.switch_to.window(driver.window_handles[-1])
                driver.maximize_window()
                sleep(20)
                driver.switch_to.frame('topFrame')

                bar()
                move_files(transfiles, fp, downloads_folder)
                transfiles = []
    #print(transfiles)
    #ic(transfiles)
    driver.quit()
    #move_files(transfiles, fp, downloads_folder)


username = getpass.getuser()    
downloads_folder = "C:/Users/" + username + "/Downloads"
current_time = datetime.now().strftime("%H:%M:%S")

def begintrans(*args):
    excel_file = easygui.fileopenbox(default="*.xlsx", filetypes=["*.xlsx", "*.xls"], title="Please select the Excel file")
    if excel_file:
        col_a, file_path = read_column(excel_file)
    else:
        cprint("No Excel file was selected.\nTerminating program...", 'light_red')
        exit()
    #ic(col_a)
    #result_pdf_files, file_path = open_path(col_a)
    goCheck(col_a, file_path)


#==============================================================================================================
# Set the width and height for the iPhone 14 screen (adjust as needed)
iphone_width = 300
iphone_height = 500
 
# Create the main window
window = tk.Tk()
window.title("Invoice Processor")
 
# Set the window size
window.geometry(f"{iphone_width}x{iphone_height}")
window.config(bg='White')
 
image = Image.open("Images/SL_Logo.png")
image = ImageTk.PhotoImage(image)
image_label = tk.Label(window, image=image, borderwidth=0)
image_label.place(x=20, y=440)

canvas = tk.Canvas(window, width=300, height=70, bg="#0014DC")
canvas.pack()
 
rectangle = canvas.create_rectangle(0, 0, 300, 70, fill="#0014DC")  # Set the rectangle coordinates and fill color
welcome_text = canvas.create_text(75, 50, text="Welcome", fill="white", font=("Sans", 20))
 
additional_text = tk.Label(window, text="This application will help you\n"
                                    "to automatize the file download\n"
                                    "process in bulk.", font=("Arial", 11), bg="white")
additional_text.place(x=45, y=100)
 
# Run the Tkinter event loop
window.mainloop()
I'm trying to add a new button and image in the function:

def read_column(excel_file)
Starting from line 48 to 56.

However, it is not appearing, hgw can I fix this?
Reply
#2
You need to keep a reference to the image. I would do it like this:
        image3 = ImageTk.PhotoImage(resimage_download)
        image_download = tk.Label(window, image=image3, borderwidth=0)
        image_download.place(x=62, y=240)

        image_download.image = image3
When you use an image in a label, tkinter does not keep a reference to the image object. image3 was the only reference to the image. When the read_column function returned, all local variables from that function cease to exist. There is no longer an image3 variable, so there is nothing that references the variable. Python assumes you no longer need the image, not a bad assumption as there is no way you can do anything with the image, so it deletes the image garbage collects the image memory.

Adding a variable to the label that references the image prevents this from happening.
Reply
#3
(Mar-06-2024, 08:50 PM)deanhystad Wrote: You need to keep a reference to the image. I would do it like this:
        image3 = ImageTk.PhotoImage(resimage_download)
        image_download = tk.Label(window, image=image3, borderwidth=0)
        image_download.place(x=62, y=240)

        image_download.image = image3
When you use an image in a label, tkinter does not keep a reference to the image object. image3 was the only reference to the image. When the read_column function returned, all local variables from that function cease to exist. There is no longer an image3 variable, so there is nothing that references the variable. Python assumes you no longer need the image, not a bad assumption as there is no way you can do anything with the image, so it deletes the image garbage collects the image memory.

Adding a variable to the label that references the image prevents this from happening.

Thank you for your reply, I tested it already but the same result, image and lable are not appearing:

 if file_path:
        files_in_folder = os.listdir(file_path) #List all the files from the folder

        image3 = Image.open("Images/Download_Logo.png")
        resimage_download = image3.resize((27,30))
        image3 = ImageTk.PhotoImage(resimage_download)
        image_download = tk.Label(window, image=image3, borderwidth=0)
        image_download.place(x=62, y=240)
        image_download.image = image3
        download_text = tk.Label(window, text="Downloading the files", font=("Arial", 9, "bold"), bg="white")
        download_text.place(x=100, y=245)
Reply
#4
If that isn't it, my next guess is that window.mainloop() is blocked from running. I tried to determine this by looking at your code, but cannot find where begintrans() gets called. Do the text labels appear? If not, that supports the mainloop getting blocked hypothesis.

This is a bit of a Frankenstein's monster wtih tkinter and easygui and selenium. I think it could be difficult keeping everyone happy.
Reply
#5
(Mar-06-2024, 10:07 PM)deanhystad Wrote: If that isn't it, my next guess is that window.mainloop() is blocked from running. I tried to determine this by looking at your code, but cannot find where begintrans() gets called. Do the text labels appear? If not, that supports the mainloop getting blocked hypothesis.

This is a bit of a Frankenstein's monster wtih tkinter and easygui and selenium. I think it could be difficult keeping everyone happy.

Hello, thanks for your reply.
begintrans is on line 218.
Reply
#6
begintrans is never called from anywhere in your code, and begintrans() is the only thing that calls read_column(). According to the posted code, you are not getting any labels because you never run the code that creates labels.
Reply
#7
(Mar-07-2024, 07:36 PM)deanhystad Wrote: begintrans is never called from anywhere in your code, and begintrans() is the only thing that calls read_column(). According to the posted code, you are not getting any labels because you never run the code that creates labels.


So does that mean we have to always run the label creation code even if we don't call Begintrans?
Reply
#8
(Mar-21-2024, 09:22 AM)JoseFullerton Wrote: So does that mean we have to always run the label creation code even if we don't call Begintrans?
This is your program. I have no idea how it is supposed to work. I'm just saying that the reason your labels don't appear is because they are not created. If you want to see the labels without calling begintrans() you need to move the label code somewhere else where it does get executed.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  tkinter destroy label inside labelFrame Nick_tkinter 3 4,677 Sep-17-2023, 03:38 PM
Last Post: munirashraf9821
  My Background Image Is Not Appearing (Python Tkinter) HailyMary 2 4,713 Mar-14-2023, 06:13 PM
Last Post: deanhystad
  [Tkinter] Load image and show in label ko_fal 8 3,223 Oct-25-2022, 09:20 AM
Last Post: ko_fal
  [Tkinter] Updating Tkinter label using multiprocessing Agusms 6 3,323 Aug-15-2022, 07:10 PM
Last Post: menator01
  simple tkinter question function call not opening image gr3yali3n 5 3,605 Aug-02-2022, 09:13 PM
Last Post: woooee
  [Tkinter] Tkinter don't change the image DQT 2 1,711 Jul-22-2022, 10:26 AM
Last Post: menator01
  [Tkinter] The Text in the Label widget Tkinter cuts off the Long text in the view malmustafa 4 5,265 Jun-26-2022, 06:26 PM
Last Post: menator01
  How to redraw an existing image to a different image TkInter zazas321 6 6,067 Jul-08-2021, 07:44 PM
Last Post: deanhystad
  [Tkinter] image in label not showing? rwahdan 2 8,463 Jun-25-2021, 10:27 AM
Last Post: rwahdan
  tkinter showing image in button rwahdan 3 5,746 Jun-16-2021, 06:08 AM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020