如何将 (Answer) 变量从 creatLabels 函数传递到 check 函数?
def createLabels(Ques):
AnswerINP = Entry(root)
AnswerINP.grid(column=3, sticky=W )
Answer = AnswerINP.get()
Checkbutton = tk.Button(root, text="CHECK", command= check)
Checkbutton.grid()
def check ():
r=requests.get('https://opentdb.com/api.phpamount='+TextINP1.get()+'&difficul)
res = r.json ()
for data in res ['results']:
if Answer.title()== data["correct_answer"]:
print("Correct")
当我以这种方式编写时,我发现变量 Answer 未定义
最佳答案
您可以使用 Lambda Expression 将变量传递给检查函数。 。 Lambda 表达式基本上是一行、匿名(未命名)函数。
为此,您只需将 Checkbuttons
命令选项更改为 lambda 表达式,并将参数添加到 check()
函数中,如下所示:
def createLabels(Ques):
AnswerINP = Entry(root)
AnswerINP.grid(column=3, sticky=W )
Answer = AnswerINP.get()
Checkbutton = tk.Button(root, text="CHECK", command=lambda a=Answer: check(a))
Checkbutton.grid()
def check (answer):
...
这应该会给你你想要的结果。
关于python - 如何将定义为 (Entry.get()) 的变量从一个函数传递到另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56309975/