Hello I'm new to python and I'm stuck I need help.
My problem is this: I have a function that returns a string I call this function in a button How to get this value ?
My code :
from tkinter import*
from tkinter import filedialog
def window():
fen=Tk() fen.geometry('{0}x{1} {2} {3}'.format(600, 400, 300, 200))
fen.config(bg = "#87CEEB")
return fen
def select_file():
file_path = filedialog.askopenfilename()
return file_path
def main():
file_path = ''
fen = window()
bouton1 = Button(fen, text = "Select a file", command= select_file())
print(file_path)
fen.mainloop()
main()
If I print the file_path in my functions I can do it, it's perfect,
But I can't get it out of the function
CodePudding user response:
You can't get the return value when the function is called as the result of an event (button press, etc). The code that calls the function (inside of mainloop
) ignores the return value.
If other parts of the code need the value, you need to store it as an attribute of an object or as a global variable.
CodePudding user response:
You wont be able to do this as you are, in theory, returning the file path to the button.
Use the function to set the variable in an object, or set a global variable.
Additionally, you dont need the lambda before your function call, just call the function without the braces (i.e. command = select_file)