TransWikia.com

Global variable to available

Stack Overflow Asked by Havard Kleven on December 23, 2021

I’ve got an issue with my code I’m simply unable to work out the error in.
Similar question was asked here. However, trying the solution did not provide me with an answer.
I’ve declared the variable file_location as global in order to have it avaible for the later code. This was the answer for aforementioned question.
I know it should be avoided, but with my experience level I do not see any other way.

Goal: I wish to write file_location to entry.

Running the code yields error

Traceback (most recent call last):
  File "C:DataPython ScriptsPDFtoText with GUI.py", line 87, in <module>
    main()
  File "C:DataPython ScriptsPDFtoText with GUI.py", line 82, in main
    app = Application()
  File "C:DataPython ScriptsPDFtoText with GUI.py", line 14, in __init__
    self.initUI()
  File "C:DataPython ScriptsPDFtoText with GUI.py", line 61, in initUI
    entry.insert(0, file_location)
NameError: name 'file_location' is not defined
>>> 

Code as follows:

from tkinter import Tk, W, E
from tkinter.ttk import Frame, Button, Entry, Style
from tkinter import filedialog as fd


class Application(Frame):

    def __init__(self):
        
        super().__init__()
        self.initUI()

        
    def initUI(self):
        
        def select_file():
            global file_location
            file_location = fd.askopenfilename(initialdir = "/C:/Users",title = "Select file",filetypes = (("PDF files","*.pdf"),("all files","*.*")))
            #print(file_location)           #Used for debugging and validating paths.


        self.master.title("PDF to Text Convertor")
        Style().configure("TButton", padding=(0, 5, 0, 5),
            font='serif 10')

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)


        btnSelect = Button(self, text="Select File", command=select_file)
        btnSelect.grid(row=1, column=0)

        entry = Entry(self)
  
        entry.insert(0, file_location)
        entry.grid(row=0, columnspan=4, sticky=W+E)
        
        btnClear = Button(self, text="Clear text")
        btnClear.grid(row=1, column=1)
      
        btnConvert = Button(self, text="Convert")
        btnConvert.grid(row=1, column=2)

        btnClose = Button(self, text="Close", command = self.master.destroy)
        btnClose.grid(row=1, column=3)

        

        self.pack()



def main():

    root = Tk()
    app = Application()
    root.mainloop()


if __name__ == '__main__':
    main()

3 Answers

The question you mentioned is different from your issue.

Your code insert them firstly.Even though you "solve" this issue by previous answer, the path wouldn't be change after you select a file

You could insert the path in the function select_file(Also could avoid using global variable.): Remove the line:

entry.insert(0, file_location)

Change your select_file function to:

def select_file():
    file_location = fd.askopenfilename(initialdir="/C:/Users", title="Select file",
                                       filetypes=(("PDF files", "*.pdf"), ("all files", "*.*")))
    # print(file_location)           #Used for debugging and validating paths.
    if file_location: # insert here.
        entry.insert("insert", file_location)

Answered by jizhihaoSAMA on December 23, 2021

You can simply define self.file_location:

from tkinter import Tk, W, E
from tkinter.ttk import Frame, Button, Entry, Style
from tkinter import filedialog as fd


class Application(Frame):

    def __init__(self):
        super().__init__()
        self.file_location = None
        self.initUI()

    def initUI(self):
        def select_file():
            self.file_location = fd.askopenfilename(initialdir="/C:/Users", title="Select file",
                                               filetypes=(("PDF files", "*.pdf"), ("all files", "*.*")))
            # print(file_location)           #Used for debugging and validating paths.

        self.master.title("PDF to Text Convertor")
        Style().configure("TButton", padding=(0, 5, 0, 5),
                          font='serif 10')

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)

        btnSelect = Button(self, text="Select File", command=select_file)
        btnSelect.grid(row=1, column=0)

        entry = Entry(self)

        entry.insert(0, self.file_location)
        entry.grid(row=0, columnspan=4, sticky=W + E)

        btnClear = Button(self, text="Clear text")
        btnClear.grid(row=1, column=1)

        btnConvert = Button(self, text="Convert")
        btnConvert.grid(row=1, column=2)

        btnClose = Button(self, text="Close", command=self.master.destroy)
        btnClose.grid(row=1, column=3)

        self.pack()


def main():
    root = Tk()
    app = Application()
    root.mainloop()


if __name__ == '__main__':
    main()

Answered by Phinnik on December 23, 2021

You should declare a global variable before any other in Python. Also there are another bug in your code. You call file_location before you initialize it. You should do select_file() before calling entry.insert(0, file_location)

from tkinter import Tk, W, E
from tkinter.ttk import Frame, Button, Entry, Style
from tkinter import filedialog as fd

file_location = None #Declare it here

class Application(Frame):

    def __init__(self):
        
        super().__init__()
        self.initUI()

        
    def initUI(self):
        
        def select_file():
            global file_location
            file_location = fd.askopenfilename(initialdir = "/C:/Users",title = "Select file",filetypes = (("PDF files","*.pdf"),("all files","*.*")))
            #print(file_location)           #Used for debugging and validating paths.


        self.master.title("PDF to Text Convertor")
        Style().configure("TButton", padding=(0, 5, 0, 5),
            font='serif 10')

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)


        btnSelect = Button(self, text="Select File", command=select_file)
        btnSelect.grid(row=1, column=0)

        entry = Entry(self)
  
        entry.insert(0, file_location)
        entry.grid(row=0, columnspan=4, sticky=W+E)
        
        btnClear = Button(self, text="Clear text")
        btnClear.grid(row=1, column=1)
      
        btnConvert = Button(self, text="Convert")
        btnConvert.grid(row=1, column=2)

        btnClose = Button(self, text="Close", command = self.master.destroy)
        btnClose.grid(row=1, column=3)

        

        self.pack()



def main():

    root = Tk()
    app = Application()
    root.mainloop()


if __name__ == '__main__':
    main()

Answered by nagyl on December 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP