0

I'm trying to import a file from a tkinter GUI to be used in the rest of my code.

import numpy as np
import tkinter as tk
from tkinter import filedialog

def FileImport():
    file = filedialog.askopenfilename()
    label = tk.Label(root, text = "Selected: "+file).pack()

root= tk.Tk() 
root.title('Main')
label = tk.Label(root, text = "Upload a file: ", fg="purple").pack()
button = tk.Button(root, text='Upload',fg="blue", command=FileImport)
button.pack()
root.mainloop()

uploaded_file = np.fromfile(file) 

Then I'm trying to perform calculation and other things on that file data.

The issue is that when I run the code the GUI works "fine", I am able to upload a file but then it tells me that name 'uploaded_file' is not defined. I think I'm missing some connection between my GUI and the rest of my code? Any advice?

Meow
  • 25
  • 4

1 Answers1

1

Adding file='' and then calling it in function with global can solve this problem. Try this:

import numpy as np
import tkinter as tk
from tkinter import filedialog
file = ''

def FileImport():
    global file
    file = filedialog.askopenfilename()
    label = tk.Label(root, text = "Selected: "+file).pack()

root= tk.Tk()
root.title('Main')
label = tk.Label(root, text = "Upload a file: ", fg="purple").pack()
button = tk.Button(root, text='Upload',fg="blue", command=FileImport)
button.pack()

root.mainloop()
uploaded_file = np.fromfile(file)
print(uploaded_file)

Hope It helps!

Ayush Raj
  • 294
  • 3
  • 14
  • Thank you but it didn't change anything. Going to try reading more about it! – Meow May 19 '20 at 17:31
  • Is it giving the same error as you have described above?? – Ayush Raj May 19 '20 at 18:00
  • Actually my bad. It does work! I was testing this in my main code and there is so much going on something else might be derailing it. Tested it in a separate file and it does work! Thanks a lot! :) – Meow May 20 '20 at 00:07