how to write the lambda expression in my tkinter ?

Chris Rebert clp2 at rebertia.com
Tue Aug 23 02:52:05 EDT 2011


2011/8/22 守株待兔 <1248283536 at qq.com>:
> from Tkinter import *
> fields = 'Name', 'Job', 'Pay'
>
> def fetch(event,entries):
>    for entry in entries:
>        print 'Input => "%s"' % entry.get()       # get text
>        print  event.widget
>
>
> def makeform(root, fields):
>    entries = []
>    for field in fields:
>        row = Frame(root)                           # make a new row
>        lab = Label(row, width=5, text=field)       # add label, entry
>        ent = Entry(row)
>        row.pack(side=TOP, fill=X)                  # pack row on top
>        lab.pack(side=LEFT)
>        ent.pack(side=RIGHT, expand=YES, fill=X)    # grow horizontal
>        entries.append(ent)
>    return entries
>
> if __name__ == '__main__':
>    root = Tk()
>    ents = makeform(root, fields)
>    root.bind('<Return>', lambda event,entries=ents: fetch(event,entries))
>    Button(root, text='Fetch', command= lambda event:fetch(event,entries)).pack(side=LEFT)
>    root.mainloop()
>
> when you run it ,press enter ,you can get the value in the entry;when you
> click the  Button(Fetch),there is a wrong output ,i can't revise it,i know
> it is the  26  can't run ,how to fix it ?
>
> Button(root, text='Fetch', command= lambda event:fetch(event,entries)).pack(side=LEFT)

Problem 1: `entries` is undefined within the scope of the lambda; it's
not a parameter of the lambda, nor is it defined in any outer scope
that encloses the lambda. This will lead to a NameError. `ents` is /
would be within scope however...(*wink*)

Problem 2: Based on quick experimentation, Tkinter does not pass
`command` any arguments, yet your lambda has 1 required argument
(namely, `event`). This will cause a run-time error when the lambda is
called.

That should be enough to get you started.

Cheers,
Chris
--
http://rebertia.com


More information about the Python-list mailing list