python - 如何将定义为 (Entry.get()) 的变量从一个函数传递到另一个函数?

标签 python function variables tkinter

如何将 (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/

相关文章:

c++ - const int function(); 之间的区别和 int func() 常量;

c++ - 协变返回类型和面向对象的编程

c++ - 什么时候引用变量合适,为什么?你能解释一下实际的语法和位置吗?

python - CreateView 中的多个表单和表单集

python - 为什么我可以重新分配 dict.update 但不能重新分配 dict.__setitem__

python - PyQt6 的 Qt 模块替代品

python - 我如何格式化我的列表以将其作为 opencv3.0 中 svm.train() 的输入

function - 函数的 Modelica 和事件生成

python - 将 bash 命令的输出保存到 if..else 语句中的变量中

php - 在 Notepad++ 中使用双击捕获 PHP 变量