'Why won't my global variables work inside the plot() function? Any suggestion is appreciated. Thanks

The function plot(), says x is not defined.

global x 
global y
global entry
global data

# Get file location
def file_location():
    filename = filedialog.askopenfilename(initialdir="Documents", title = "select a file", filetypes = ((("all files", "*.*"), ("txt files", "*.txt")))) #This gets the name

    data = list()
    y = data
    x = np.arange(len(data))
    
    try:
        with open (filename) as f:
            for i in range(0):
                data.append(f.readlines().split())
            for lines in f:
                data.append((float(lines.strip())))
    except:
        print("Error: Check the file format. One data per line. No comma needed.")

    fit = np.polyfit(x,y, int(entry.get()))
    plt.plot(x,y)
    plt.plot(x, np.polyval(fit, x))
    plt.show()
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\FredericoDiogo\anaconda3\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:\Users\FREDER~1\AppData\Local\Temp/ipykernel_24312/396139393.py", line 24, in plot
    fit = np.polyfit(x,y, int(entry.get()))
NameError: name 'x' is not defined


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source