Search code examples
pythonpython-3.xuser-inputtkinter-entry

How to return back from a function only after certain condition is satisfied


How do i return back from the function "prompt" only if and after the user has entered the input in entry widget to the function which has called it.

def prompt(to_speak,label_text,prompt):
   name = ""
   main = Toplevel()
   label = Label(main,text = label_text)
   label.grid()
   var = StringVar()
   entry = Entry(main)
   entry.focus()
   entry.grid()
   entry.config(textvariable = var)

   def get_input():
      print("function call has occured")

      global name
      name = var.get()
      if not input:
          speak(prompt)
      else:
          main.destroy()

   button = Button(main,text = "Proceed",fg = "white",bg = "#1287A8",command =  get_input)
   button.grid()
   speak(to_speak)



   if name:
      return name
   main.mainloop()

I have defined the call back function "get_input" to get the input from entry widget once the "proceed" button is pressed. It would check whether the user has entered the input or not. If entered it would destroy the Toplevel and I wanted that input to be returned to the function which has called "prompt", if the user has not entered the input it would warn the user.

But if the user has entered the input, then i would want to return that input to the function which has called "prompt" function.

I tried to implement it using if condition, but if condition is checked only once and that too much before the "Proceed" button is pressed.

Is it possible to check the "if" condition every time after the "get_input" function is executed.

Or else is there any other way to achieve this?


Solution

  • As mentioned in the comment

    Tkinter.Widget.wait_window-method

    I wanted the widget "main" to be destroyed only after the user has entered the input and return the value entered by user to the caller function. The wait_window() exactly does this.

        main.wait_window(main) #in my case the parent widget is main and the widget to be destroyed is also main.      
        return name
    

    The statements after wait_window() will not be executed until the desired widget is destroyed.Only after the intended widget is destroyed the statements following wait_window() will be executed.

    So here the main widget will not be destroyed until the user enters the input, once he enters the input, the main widget is destroyed and the statement below wait_window() i.e return name gets executed.