Reputation: 21
I'm not sure what im doing wrong in my code (below). I'm trying to get a function that would run and also return the result in a variable y. The idea is to have the user click on the select file button which would open the dialog box then once the user selected a file, save the file path to the variable y so that i can use it elsewhere in my code
Any help would be appreicated
from tkinter import Tk, Button, filedialog, Label
root = Tk()
root.title("test")
# Create a button with a custom callback
def openfiledialog():
global y
y = filedialog.askopenfilename(initialdir = "/",title = "Select f .
ile",filetypes = (("text file","*.txt"),("all files","*.*")))
return y
print(y)
file_button = Button(root, text='Select File', command=openfiledialog)
file_button.pack()
exit_button = Button(root, text='Exit Program', command=root.destroy)
exit_button.pack()
w = Label(root, text='\n'"Step 1: Make sure the URL's in file are
properly formatted, one URL per line"'\n''\n'
"Step 2: Select file"'\n''\n'
"Step 3: click run")
w.pack()
root.mainloop()
Upvotes: 0
Views: 4719
Reputation: 15226
You do not need to return a value when you are directly assigning the value to a global variable.
I also think the way you have written your Label is unorthodox. What you want to do can be done with one set of quotes.
When I have a known global variable I define it first before anything.
Your print(y)
statement does not work as you think it does. It is only being run one time at the start of your program and at the moment it runs y
is not equal to anything.
You need to move the print statement into the function.
Update: I have added a button to help with your below comment.
This button will print the current stored value of y
.
The below code is a rework of your code.
from tkinter import Tk, Button, filedialog, Label
root = Tk()
y = ""
root.title("test")
def openfiledialog():
global y
y = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("text file","*.txt"),("all files","*.*")))
def check_path():
global y
print(y)
file_button = Button(root, text='Select File', command=openfiledialog)
file_button.pack()
exit_button = Button(root, text='Exit Program', command=root.destroy)
exit_button.pack()
w = Label(root, text="\nStep 1: Make sure the URL's in file are properly formatted, one URL per line\n\nStep 2: Select file\n\nStep 3: click run")
w.pack()
Button(root, text="Print current saved path", command = check_path).pack()
root.mainloop()
Upvotes: 2