简体   繁体   中英

How do I populate the entry widget when I press the Browse button in tkinter?

I have the following code which serves the purpose of opening a GUI which would allow me to browse a file from a specified path, then after clicking the submit button, the web page gets populated online from an xlsx file and the output of the web page is again stored in an output xlsx file. My code does all the objectives. But there is an issue- I have a browse button beside the edit widget which allows me to browse through the file path to fetch the input file in my GUI. Now the moment I press the browse button, although it fetches the file but it puts the file path beside the browse button like this: enter image description here

The code is this:

from tkinter import *
from tkinter import messagebox as msg
from tkinter import filedialog as fd
from tkinter import ttk

class GUI: 
    
    def __init__(self,master):
    
    
        master.title("Webscraper")
    
        self.LabelFrame=ttk.Labelframe(master)
        self.LabelFrame.grid(row=0,column=3)
    
    self.ip_word  = Label(master,text="File Path")
    self.ip_word.grid(row=0,sticky=E) 
    
    self.path_field = Entry(master)
    self.path_field.grid(row=0,column=1,sticky=W)
    
    self.browse_file=Button(master,text="Browse",command=self.file_found)
    self.browse_file.grid(row=0,column=2,sticky=E)
    #self.path_field=self.path_browse.get()
    
    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.printMessage )
    self.Submit.grid(row=5,column=1)
    
    self.quit_button=Button(master,text="Quit",command= master.destroy)
    self.quit_button.grid(row=5,column=2)
    
def file_found(self):
    
    self.path_browse=fd.askopenfilename(initialdir="/",title="Select A file",filetype=(("Excel Workbook","*.xlsx"),("All Files","*.*")))
    self.label=ttk.Label(self.LabelFrame,text="")
    self.label.grid(row=1,column=1)
    self.label.configure(text=self.path_browse)
    self.path_field.bind("<Return>",self.path_browse)
    
    
def printMessage(self):
    
    str1=self.path_field.get()
    str2=self.filename.get()
    self.Scraper(str1,str2)
 


def Scraper(self,path_field,filename):
    import pandas as pd
    import os
    # "C:/Users/chowdhuryr/Desktop/first automation/MAIN RESEARCH DATA.xlsx"
    user_path =path_field #input file path of your file
    
    if os.path.exists(user_path):
           df = pd.read_excel(user_path, sheetname='Sheet1')
           print("File Found and We are Processing !")
    else:  
        print ("Input Directory does not exists.")
        
    head, tail = os.path.split(user_path)
    path=head+"/"
    output=filename
    #"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]
        image_name=path+str+".png"  #Taking the circuit id name 
        driver.get_screenshot_as_file(image_name)
    
        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 
    user_output=path+output+".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()
    
    
    #-------------------------------------------------------------------------------------------------------------------------------------------
    self.popup()
    #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 """
    
def popup(self):
   msg.showinfo("your process is completed.")



root =Tk()
b=GUI(root) 
root.mainloop()

The part of the code :

self.browse_file=Button(master,text="Browse",command=self.file_found)
self.browse_file.grid(row=0,column=2,sticky=E)

calls the file_found() which browses through the path to get the file but this does not populate the

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

where the self.path_field is the entry widget that should be populated by the file path obtained by the browse button.

Well; as I understand it you want the file path in the entry and not in a separate Label. But in your code you put it in a separate label and not in the entry...

Here is an example of how to put the path in the entry:

def file_found(self):
    self.path_browse=fd.askopenfilename(initialdir="/",title="Select A file",
        filetype=(("Excel Workbook","*.xlsx"),("All Files","*.*")))
    self.path_field.delete(0,END)    # Remove any previous content
    self.path_field.insert(0,self.path_browse)  # Insert new content

I'm not really clear about what you seek to accomplish with the line:

self.path_field.bind("<Return>",self.path_browse)

It binds a Return in the path_field entry to a variable...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM