【问题标题】:How do I pass a variable defined as (Entry.get()) from one function to another?如何将定义为 (Entry.get()) 的变量从一个函数传递到另一个函数?
【发布时间】:2019-05-26 01:26:35
【问题描述】:

如何将 creatLabels 函数中的 (Answer) 变量传递给检查函数?

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

当我以这种方式编写时,我得到那个变量答案没有定义

【问题讨论】:

    标签: python function variables tkinter


    【解决方案1】:

    您可以使用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):
        ...
    

    这应该会给你想要的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2021-04-23
      • 1970-01-01
      相关资源
      最近更新 更多