Search code examples
pythontkinterjupyter-notebooktkinter-entry

How can I assign the text imputed into an entry box (tkinter) to variable in python script and run the script by pressing a button?


I have a python script that takes the file path and runs the following script:

    file = 'C:/Users/crist/Downloads/Fraction_Event_Report_Wednesday_June_16_2021_20_27_38.pdf'
    
    lines = []
    with pdfplumber.open(file) as pdf:
        pages = pdf.pages
        for page in pdf.pages:
            text = page.extract_text()
            print(text)

I have created an entry box with tkinter:

     import tkinter as tk

master = tk.Tk()
tk.Label(master, 
         text="File_path").grid(row=0)

e = tk.Entry(master)


e.grid(row=0, column=1)


tk.Button(master, 
          text='Run Script', 
          command=master.quit).grid(row=3, 
                                    column=0, 
                                    sticky=tk.W, 
                                    pady=4)

tk.mainloop()

I would like to assign the File_path imputed in the entry box by the user to the "file" in the script and run the script when pressing the "Run Script" button. How can I do that?


Solution

  • It's better to spawn a file dialog instead of using a tkinter.Entry:

    # GUI.py
    from tkinter.filedialog import askopenfilename
    import tkinter as tk
    
    # Create the window and hide it
    root = tk.Tk()
    root.withdraw()
    
    # Now you are free to popup any dialog that you need
    filetypes = (("PDF file", "*.pdf"), ("All files", "*.*"))
    filepath = askopenfilename(filetypes=filetypes)
    
    # Now use the filepath
    lines = []
    with pdfplumber.open(filepath) as pdf:
        ...
    
    # Destroy the window
    root.destroy()