从 tkinter 调用变量路径

问题描述 投票:0回答:1

我正在Python中运行一个代码,它分为两部分,第一个部分是在页面上执行网页抓取的函数,第二个部分是使用tkinter打开一个界面,供用户选择一个包含信息的文件夹已保存。 问题是我无法将用户选择的路径传递给我的网络抓取代码。你能帮我解决这个问题吗?

import tkinter
from tkinter import messagebox,ttk
from tkinter.filedialog import askdirectory
from tkinter.filedialog import FileDialog

######################################
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.common.exceptions import NoSuchElementException
import time
import IntegracaoRestTotvs #importa a funcao de integracao
import ConectaFTP #importa funcao de conexão com o ftp
import os

def geraarquivos():
    #função de integração
    x = IntegracaoRestTotvs.chamaapi()  # Chama a função
    if x:  # Verifica se a função retornou algo
        for item in x:
            matricula = item['matricula']  # Pega a matrícula
            nome = item['nome']  # Pega o nome
            print(f"Matrícula: {matricula}, Nome: {nome}")  # Exibe matrícula e nome
            #print(matricula)  # Imprime cada matrícula
            #print(nome)
            options = webdriver.ChromeOptions()
            options.add_argument("start-maximized") #
            options.add_experimental_option("excludeSwitches", ["enable-automation"])
            options.add_experimental_option('useAutomationExtension', False)
            options.add_experimental_option("detach", True)
            # download
            options.add_experimental_option('prefs', {
            "download.default_directory": "C:\\Users\\Lenovo NtBk2\\Downloads\\pdfs", #Change default directory for downloads
            #"download.prompt_for_download": False, #To auto download the file
            #"download.directory_upgrade": True,
            "plugins.always_open_pdf_externally": True #It will not show PDF directly in chrome 
            })

            driver = webdriver.Chrome(options=options)
            driver.get("xxxxx")

           
            WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name^='a-'][src^='https://www.google.com/recaptcha/api2/anchor?']")))
            WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[@id='recaptcha-anchor']"))).click()
            driver.switch_to.default_content()

            search = driver.find_element("name","inscricao")
            search.send_keys(matricula)
            search.send_keys(Keys.TAB)
            time.sleep(5)

            try:
                envia = driver.find_element(By.XPATH, "//button[text()='Emitir']")
                envia.click()
                time.sleep(5)
                t = driver.find_element(By.XPATH, "(//*[name()='path'][@fill='currentColor'])[18]")
                time.sleep(2)
                t.click()  
                time.sleep(5)
                driver.quit()
                os.rename('C:\\Users\\Lenovo NtBk2\\Downloads\\pdfs\\Documento de Arrecadação Municipal de Taxa de IPTU.pdf', "C:\\Users\\Lenovo NtBk2\\Downloads\\pdfs\\"+nome+".pdf")
            except:
                print("boleto já gerado!")
                driver.quit()
    ConectaFTP.conectaftp()


lista =["emp1", "outros"]
caminho = ""
root=tkinter.Tk()
root.geometry('400x200')
root.title("Importação Boletos")
empreendimento_label=tkinter.Label(root,text="Seleção de Empreendimento:")
empreendimento_label.pack(anchor=tkinter.W,padx=10)
empreendimento_dropdown = ttk.Combobox(root,values=lista)
empreendimento_dropdown.pack(anchor=tkinter.W,padx=10)



def Selecione_Arquivo():
    caminho = askdirectory()
    pasta_label.config(text=caminho)


botao_pasta = ttk.Button(root,text="Selecione a Pasta",command=Selecione_Arquivo)
botao_pasta.place(x=10,y=50)

pasta_label=tkinter.Label(root,text=caminho)
pasta_label.pack(anchor=tkinter.W,padx=10,pady=35)


botao_executa = ttk.Button(root, text="Executar",command= lambda: geraarquivos())
botao_executa.place(x=10,y=100)



root.mainloop()

例如,我需要将第 84 行返回的路径应用到第 36 行和第 64 行

我尝试生成新函数来存储变量并更改字段的顺序

python selenium-webdriver tkinter path
1个回答
0
投票

根据给出的代码简单回答?只需向您的

geraarquivos
函数添加一个默认参数,并将路径传递给您用于按钮命令的 lambda -
lambda: geraarquivos(pasta_label.cget('text'))

© www.soinside.com 2019 - 2024. All rights reserved.