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?

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you but it didn't change anything. 🤷 Going to try reading more about it!
Is it giving the same error as you have described above??
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! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.