从一个函数访问另一个函数中的变量

问题描述 投票:0回答:1

这是我的代码:

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()

在搜索函数 (

requests.get("https://pokeapi.co/api/v2/pokemon/" + str(window().pokemon))
) 中,我尝试访问可在
pokemon
函数中找到的
window
变量。然而由于某种原因它似乎不想合作,我尝试使用
window.pokemon
window.pokemon()
window().pokemon
。我唯一需要做的就是删除窗口函数并将所有代码放在全局级别的窗口函数内。但我更愿意将所有这些都放在一个函数中。如有任何帮助,我们将不胜感激。

python-3.x function tkinter
1个回答
0
投票

您可以将输入值作为参数传递给

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)
...
© www.soinside.com 2019 - 2024. All rights reserved.