#๐Ÿ”’ returning a value from a nested function

11 messages ยท Page 1 of 1 (latest)

sterile pollen
#
    def get_file_name():
      file_name = ""
      # Button action function
      def on_enter():
          global file_name
          file_name = entry.get()
          return file_name
  
      # Create main window
      root = tk.Tk()
      root.title("Tkinter Layout Example")
      root.geometry("350x100")
  
      # Create and place the label
      label = ttk.Label(root, text="Enter your text:", font=("Arial, 16"))
      label.pack(pady=(10, 5))  # Padding: 10px top, 5px bottom
  
      # Create a frame for the entry and button
      frame = ttk.Frame(root)
      frame.pack(pady=5, padx=10, fill=tk.X)
  
      # Create and place the entry field
      entry = ttk.Entry(frame)
      entry.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=(0, 5))  # Expands to take available space
  
      # Create and place the enter button
      enter_button = ttk.Button(frame, text="Enter", command=on_enter)
      enter_button.pack(side=tk.RIGHT)
  
      # Run the application
      root.mainloop()


I'm importing this function to a seperate file, and i want it to work such that when on_enter is called, the get_file_name will return the same as what on_enter returned

snow plankBOT
#

@sterile pollen

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

sterile pollen
#

i think the indenting got messed up on discord but its all properly indented in my editor

manic escarp
#

why did you define a function inside a function?

sterile pollen
#

its tkinter, in my main file i have it such that once i press a button, another tkinter window opens

#

so the get_file_name opens a new tkinter window

#

and the nested function is a button command of that window

#

if that makes sense

#

!CLOSE

snow plankBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.