Menus with Tkinter ??

John Grayson johngrayson at home.com
Mon Sep 11 19:02:44 EDT 2000


In article <slrn8rqs9u.4j4.thor at localhost.localdomain>,
  irmina at ctv.es wrote:
> On Mon,  Carles Sadurní Anguita <isard at localhost.localdomain> wrote:
> >Hello,
> >
> >I'm learning python and tkinter and I've found an amazing "problem".
Why
> >does this code work
> >
> >--------------------- This code works --------------
> >#!/usr/bin/python
> >from Tkinter import *
> >
> >def ah():
> >	print "Ah!"
> >def oh():
> >	print "Oh!"
> >
> >root = Tk()
> >menubar = Menu(root)
> >menuarxiu = Menu(menubar, tearoff=0)
> >menuarxiu.add_command(label="Ah!", command=ah)
> >menuarxiu.add_command(label="Oh!", command=oh)
> >menubar.add_cascade(label="arxiu", menu=menuarxiu)
> >root.config(menu = menubar)
> >mainloop()
> >----------------------------------------------------
> >
> >and this one doesn't
> >
> >
> >--------------------- This code doesn't work -------
> >
> >#!/usr/bin/python
> >from Tkinter import *
> >
> >def ah(n):
> >	print n
> >
> >root = Tk()
> >menubar = Menu(root)
> >menuarxiu = Menu(menubar, tearoff=0)
> >menuarxiu.add_command(label="Ah!", command=ah(0))
> >menuarxiu.add_command(label="Oh!", command=ah(1))
> >menubar.add_cascade(label="arxiu", menu=menuarxiu)
> >root.config(menu = menubar)
> >mainloop()
> >____________________________________________________
> >
> >
> >It prints 0 and 1 before the user pops the menu!
> >
>
> Well,
> menuarxiu.add_command(label="Ah!", command=<reference to function>)
>
> "ah" is a reference to function.
> ah(0) is a call to a function.
>
> ---
> MGA
>

Cardinal Fang! Bring me the lambda!

Change:

     menuarxiu.add_command(label="Ah!", command=ah(0))
     menuarxiu.add_command(label="Oh!", command=ah(1))

to:

     menuarxiu.add_command(label="Ah!", command=lambda x=0: ah(x))
     menuarxiu.add_command(label="Oh!", command=lambda x=1: ah(x))


John Grayson



Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list