python-3.xfunctionapitkinter

Access variable from one function inside other function


This is my code:

from tkinter import *
from tkinter import ttk
import requests

def window():
    root = Tk()
    root.title("Nils' Pokedex")
    
    # Styling window
    s = ttk.Style()
    s.configure('Danger.TFrame', background='red', borderwidth=5, relief='raised')
    ttk.Frame(root, width=200, height=200, style='Danger.TFrame').grid()

    mainframe = ttk.Frame(root, padding="3 3 12 12")
    mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)

    pokemon = StringVar() # Search bar Creation
    pokemon_entry = ttk.Entry(mainframe, width=7, textvariable=pokemon)
    pokemon_entry.grid(column=2, row=1, sticky=(W, E))

    ttk.Button(mainframe, text="Search", command=search).grid(column=3, row=3, sticky=W) # Search Button

    for child in mainframe.winfo_children():
        child.grid_configure(padx=5, pady=5)
    
    pokemon_entry.focus()
    root.bind("<Return>", search) # Bind 

    

    root.mainloop()

def search(*args):
    response = requests.get("https://pokeapi.co/api/v2/pokemon/" + str(window().pokemon)) # Fetching API
    answer = response.json()
    print(answer)

window()

inside the search function (requests.get("https://pokeapi.co/api/v2/pokemon/" + str(window().pokemon))) im trying to access the pokemon variable that can be found in the window function. However for some reason it doesn't seem to want to cooperate, I tried using window.pokemon and window.pokemon() and window().pokemon. The only thing I got to work was to remove the window function and have all the code inside the window function on the global level. But I'd much rather have all of it inside a function. Any help is appreciated.


Solution

  • You can pass the input value as an argument to search():

    ...
    def window():
        ...
        ttk.Button(mainframe, text="Search", command=lambda:search(pokemon.get())).grid(column=3, row=3, sticky=W) # Search Button
        ...
        root.bind("<Return>", lambda e: search(pokemon.get())) # Bind
    
        root.mainloop()
    
    def search(pokemon):
        response = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon}") # Fetching API
        answer = response.json()
        print(answer)
    ...