Tkinter: An image and label are not appearing. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: Tkinter: An image and label are not appearing. (/thread-41718.html) |
Tkinter: An image and label are not appearing. - emont - Mar-06-2024 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? RE: Tkinter: An image and label are not appearing. - deanhystad - Mar-06-2024 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 = image3When 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. RE: Tkinter: An image and label are not appearing. - emont - Mar-06-2024 (Mar-06-2024, 08:50 PM)deanhystad Wrote: You need to keep a reference to the image. I would do it like this: 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) RE: Tkinter: An image and label are not appearing. - deanhystad - Mar-06-2024 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. RE: Tkinter: An image and label are not appearing. - emont - Mar-07-2024 (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. Hello, thanks for your reply. begintrans is on line 218. RE: Tkinter: An image and label are not appearing. - deanhystad - Mar-07-2024 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. RE: Tkinter: An image and label are not appearing. - JoseFullerton - Mar-21-2024 (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? RE: Tkinter: An image and label are not appearing. - deanhystad - Mar-21-2024 (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. |