如何将动态参数作为参数传递

时间:2018-09-17 12:18:51

标签: python-3.x tkinter

我有以下代码:

from tkinter import *


class GUI: 

    def __init__(self,master):


        self.ip_word  = Label(master,text="Input Path")
        self.ip_word.grid(row=0,sticky=E)   

        self.ip_path_field = Entry(master)
        self.ip_path_field.grid(row=0,column=1,sticky=W)

        self.op_word  = Label(master,text="Output Path")
        self.op_word.grid(row=2,sticky=E)

        self.op_path_field = Entry(master)
        self.op_path_field.grid(row=2,column=1,sticky=W)

        self.filename_word=Label(master,text="Output Filename ")
        self.filename_word.grid(row=4,sticky=E)

        self.filename =Entry(master)
        self.filename.grid(row=4,column=1,sticky=W)

        self.Submit = Button(master,text="Submit",fg="black",bg="white",command=self.Scrapper(ip_path_field,op_path_field,filename) )
        self.Submit.grid(row=5,columnspan=2)
    """        
    def printMessage(self):
        str1=ip_path_field
        str2=op_path_field
        str3=filename
        Scrapper(str1,str2,str3)"""



    def Scrapper(self,ip_path_field,op_path_field,filename):
        import pandas as pd
        import os
        # "C:/Users/chowdhuryr/Desktop/first automation/MAIN RESEARCH DATA.xlsx"
        user_input =ip_path_field#input("Enter the input file path of your file: ")

        if os.path.exists(user_input):
               df = pd.read_excel(user_input, sheetname='Sheet1')
               print("File Found and We are Processing !")
        else:  
            print ("Input Directory does not exists.")
        #"C:/Users/chowdhuryr/Desktop/first automation/OUTPUT DATA.xlsx"
        user_output =op_path_field#input("Enter the output file path of your file: ")

        #if os.path.exists(user_input):
               #df = pd.read_excel(user_input, sheetname='Sheet1')
        #--------------------------------------------------------------------------------------------------------------------------------------
        #setting up the path 
        import os
        os.chdir('C:/Users/chowdhuryr/Desktop/first automation')

        df=df[0:5]
        #--------------------------------------------------------------------------------------------------------------------------------------
        #importing necessary packages 
        from selenium import webdriver 
        #from selenium.webdriver.common.keys import Keys
        from selenium.common.exceptions import NoSuchElementException

        #---------------------------------------------------------------------------------------------------------------------------------------


        #Setting up Chrome webdriver 
        #chrome_options = webdriver.ChromeOptions()
        options = webdriver.ChromeOptions()
        options.add_argument("--headless") #making the window work in the background
        options.add_argument('window-size=1200x850')


        #declaring a list to store the messages 
        Message=list()

        Tier=list()

        Wirecentre=list()



        #---------------------------------------------------------------------------------------------------------------------------------------
        #iteration to access the url and and retriving the Tier Locations 

        for i in range(0,df.shape[0]): #(0,df.shape[0]):

            driver = webdriver.Chrome(executable_path='C:/Users/chowdhuryr/Desktop/first automation/chromedriver', chrome_options=options) #openning chrome
            #driver.maximize_window() #maximizing the window 

            driver.get('https://clec.att.com/facilitiescheck/facilities_chk.cfm') #openning the url 

            street_address=driver.find_element_by_xpath('/html/body/form/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[2]/input') #accessing the street address field 
            street_address.send_keys(df['CIRCUIT_LOC_ADDR'][i].split(',')[0])  #passing the values to street_address location 

            city=driver.find_element_by_xpath('/html/body/form/table[1]/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]/input') #accessing the city to street address field 
            city.send_keys(df['CIRCUIT_LOC_ADDR'][i].split(',')[1]) #passing the values to the city location 

            state=driver.find_element_by_xpath('/html/body/form/table[1]/tbody/tr[2]/td[2]/table/tbody/tr[4]/td[2]/select') #accessing the state field 
            state.send_keys(df['CIRCUIT_LOC_ADDR'][i].split(',')[2]) #passing the values to the state field 

            checkbox=driver.find_element_by_xpath('/html/body/form/table[1]/tbody/tr[2]/td[2]/table/tbody/tr[8]/td[1]/input') #accessing the checkbox 
            checkbox.click()  #clicking on the check box 

            search_button=driver.find_element_by_xpath('/html/body/form/table[1]/tbody/tr[2]/td[2]/table/tbody/tr[8]/td[1]/input') #accessing the submit button 
            search_button.submit() #clicking the submit button 

            #try-except block in case if radio button appears 
            try:
                Address=driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[1]/td[2]/b') #taking the xpath of the address block 
                if (Address):         #checking if it contains any radio button or not 
                    Radio_button=driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/td[1]/input') #getting the xpath of radio button 
                    Radio_button.click()   #clicking the radio button                                                                           
                    submit_button=driver.find_element_by_xpath('/html/body/form/table[3]/tbody/tr[2]/td/input') #getting the submit button
                    submit_button.submit()
            except NoSuchElementException:
                 print('no such element found')




            message_body= driver.find_element_by_xpath('//*[@id="msg"]/table/tbody/tr/td').text #Extracting the Message from the message box 
            Message.append(message_body[14:]) #putting the message into a text 

            str = message_body.split() #splitting the message 

            if any ("Tier"in s for s in str):
               j=str.index('Tier')
               Tier.append(str[j+1])
            else:
               Tier.append("NULL")

            if any ("AT&T"in s for s in str):
               j=str.index('AT&T')
               Wirecentre.append(str[j+1])
            else:
               Wirecentre.append("NULL")

            #saving the screenshot 
            str=df['STRIP_EC_CIRCUIT_ID'][i]
            filename="C:\\Users\\chowdhuryr\\Desktop\\first automation\\"+str+".png"  #Taking the circuit id name 
            driver.get_screenshot_as_file(filename)

            driver.close() #closiing the driver 

        #------------------------------------------------------------------------------------------------------------------------------------------

        #putting the back thenew columns into the dataframe and storing it into an excel sheet 

        df['Tier']=Tier   #putting the Tier column back into the dataset 
        df['Wirecentre']=Wirecentre #putting the Wirecentre column back into the dataset 
        df['Message']=Message  #putting the Message column back into the dataset 
        if os.path.exists(user_output):
            user_output="user_output"+filename+".xlsx"
            writer = pd.ExcelWriter(user_output)    #writing the dataframe down into a new excel file 
            df.to_excel(writer,'sheet1',index=False)        #to_excel(writer,'Sheet1')    
            writer.save()
        else:
            print ("Output Directory does not exists.")


        #-------------------------------------------------------------------------------------------------------------------------------------------

        #Generating pop up window at the end of the process 
        popup_driver=webdriver.Chrome()
        popup_driver.maximize_window()
        popup_driver.execute_script(" window.alert('Process is Completed');") #generating the pop up """





root =Tk()
b=GUI(root) 
#b.Scrapper(ip_path_field,op_path_field,filename)   
root.mainloop()

现在我要做的是:

我想将变量ip_path_field,op_path_field,文件名作为参数传递给名为Scrapper的函数。现在ip_path_field,op_path_field,文件名都是用户输入,而不是硬编码的字符串。现在,每当我运行以下代码时,便会打开GUI,并且每当在所需的编辑框中提供输入内容并按Submit按钮时,都会得到以下未定义的错误名称“ ip_path_field”。这段代码的目的是将用户定义的文件路径传递到上面的代码中定义的名为Scrapper()的函数。

2 个答案:

答案 0 :(得分:3)

您需要创建一个获取值的回调,然后将它们传递给执行工作的函数。

示例:

class GUI: 

    def __init__(self,master):
        ...
        self.Submit = Button(..., command=self.handle_submit)
        ...

    def handle_submit(self):
        ip_path = self.ip_path_field.get()
        op_path = self.op_path_field.get()
        filename = self.filename.get()

        self.Scrapper(ip_path_field,op_path_field,filename)

答案 1 :(得分:0)

您遇到的主要问题与如何构建方法有关。相反,您应该将unsubscribe调用放入该方法中。这样,您可以简单地运行命令来调用scraper,而无需传递参数。我已将您的代码重新编写为更严格地遵循PEP8标准并包括方法更正。

您只需要将Observable前缀应用于类属性/方法。标签/按钮之类的内容在以后的代码中不会被修改,应该留作普通的窗口小部件,而这些窗口小部件未分配为属性。

接下来,我将所有导入内容移到代码的顶部。您只需要一次导入一个库,并且所有库都应列在代码的顶部。请记住,对于导入,最好使用get()而不是使用self.来防止意外覆盖。

我已将您的字符串连接更改为不推荐使用import tkinter as tk的{​​{1}}方法。

这是您的代码,还进行了一些基本清理。

*

所有这些都表示您下次应该尝试使用最少的代码。当您将问题缩小到确切范围时,更容易解决问题。例如,根据您的问题,Minimal, Complete, and Verifiable example看起来像这样。

format()