Search code examples
pythontkinterreturn-value

Python tkinter return value from function call in a button


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 
file_path = ''
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():  
  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


Solution

  • 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.

    The other problem in your revised code is that you're calling the print statement before the user has a chance to click the button, so the value will be blank even if you use a global variable. You have to wait to use the value until after you've clicked the button and selected the file.

    For example, create a function that prints the value, and then attach that function to a button. Click your button to choose the file, and then click the button to display the data. As long as you save the value in the first function into a global variable, it will be available in the second function.