首页 文章

在Tkinter的'command = '中使用lambda函数 .

提问于
浏览
2

这是一个非常容易理解的代码:

主要:

import pdb
#pdb.set_trace()
import sys
import csv
sys.version_info
  
if sys.version_info[0] < 3:
  from Tkinter import *
else:
  from tkinter import *


from Untitled import *

main_window =Tk()
main_window.title("Welcome")


label = Label(main_window, text="Enter your current weight")
label.pack()
Current_Weight=StringVar()
Current_Weight.set("0.0")
entree1 = Entry(main_window,textvariable=Current_Weight,width=30)
entree1.pack()
bouton1 = Button(main_window, text="Enter", command= lambda evt,Current_Weight,entree1: get(evt,Current_Weight,entree1))
bouton1.pack()

在另一个文件Untitled我有“获取”功能:

def get (event,loot, entree):
    loot=float(entree.get())
    print(loot)

当我运行主时我收到以下错误:

Tkinter回调中的异常回溯(最近一次调用最后一次):文件“/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/idlelib/run.py”,第121行,在主要seq中,request = rpc.request_queue.get(block = True,timeout = 0.05)文件“/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/queue.py”,第175行,在get raise Empty queue.Empty

在处理上述异常期间,发生了另一个异常:

回溯(最近一次调用最后一次):文件“/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/ init .py”,第1533行,在 call 中返回self.func(* args)TypeError :()缺少3个必需的位置参数:'evt','Current_Weight'和'entree1'

我怎么解决这个问题?

我认为lambda函数允许我们在依赖于事件的函数中使用一些args .

1 回答

  • 6

    command lambda根本没有任何参数;此外,没有 evt 你可以 grab . lambda可以引用它之外的变量;这被称为闭包 . 因此你的按钮代码应该是:

    bouton1 = Button(main_window, text="Enter",
        command = lambda: get(Current_Weight, entree1))
    

    你的_761449应该说:

    def get(loot, entree):
        loot = float(entree.get())
        print(loot)
    

相关问题