473,386 Members | 1,715 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Tkinter.Button(... command) lambda and argument problem

Jay
I'm having a problem using lambda to use a command with an argument for
a button in Tkinter.

buttons = range(5)
for x in xrange(5):
buttons[x] = Button(frame, text=str(x+1), command=lambda:
self.highlight(x))
buttons[x].pack(side=LEFT)

The buttons are correctly numbered 1 through 5, but no matter which
button I click on, it sends the number 4 as an argument to the
highlight function. How can I correct this?

By the way, I've tried changing xrange to range with no success.

Sep 15 '06 #1
8 8094
"Jay" <ja*******@gmail.comwrites:
I'm having a problem using lambda to use a command with an argument for
a button in Tkinter.

buttons = range(5)
for x in xrange(5):
self.highlight(x))
buttons[x].pack(side=LEFT)

The buttons are correctly numbered 1 through 5, but no matter which
button I click on, it sends the number 4 as an argument to the
highlight function.
x is not bound by the lambda and so the lambda body gets it from the
outside environment at the time the body is executed. You have to
capture it at the time you create the lambda. There's an ugly but
idiomatic trick in Python usually used for that:

buttons[x] = Button(frame, text=str(x+1), \
command=lambda x=x: self.highlight(x))

See the "x=x" gives the lambda an arg whose default value is set to
x at the time the lambda is created, as opposed to when it's called.
Sep 15 '06 #2
Jay
Perfect. Thanks.
Paul Rubin wrote:
"Jay" <ja*******@gmail.comwrites:
I'm having a problem using lambda to use a command with an argument for
a button in Tkinter.

buttons = range(5)
for x in xrange(5):
self.highlight(x))
buttons[x].pack(side=LEFT)

The buttons are correctly numbered 1 through 5, but no matter which
button I click on, it sends the number 4 as an argument to the
highlight function.

x is not bound by the lambda and so the lambda body gets it from the
outside environment at the time the body is executed. You have to
capture it at the time you create the lambda. There's an ugly but
idiomatic trick in Python usually used for that:

buttons[x] = Button(frame, text=str(x+1), \
command=lambda x=x: self.highlight(x))

See the "x=x" gives the lambda an arg whose default value is set to
x at the time the lambda is created, as opposed to when it's called.
Sep 15 '06 #3
In that case you don't need a lambda:

import Tkinter as tk

class Test:
def __init__(self, parent):
buttons = [tk.Button(parent, text=str(x+1),
command=self.highlight(x)) for x in range(5)]
for button in buttons:
button.pack(side=tk.LEFT)

def highlight(self, x):
print "highlight", x

root = tk.Tk()
d = Test(root)
root.mainloop()

Bye,
bearophile

Sep 16 '06 #4
Jay
Thanks for the tip, but that breaks things later for what I'm doing.

be************@lycos.com wrote:
In that case you don't need a lambda:

import Tkinter as tk

class Test:
def __init__(self, parent):
buttons = [tk.Button(parent, text=str(x+1),
command=self.highlight(x)) for x in range(5)]
for button in buttons:
button.pack(side=tk.LEFT)

def highlight(self, x):
print "highlight", x

root = tk.Tk()
d = Test(root)
root.mainloop()

Bye,
bearophile
Sep 16 '06 #5

Jay wrote:
Thanks for the tip, but that breaks things later for what I'm doing.

be************@lycos.com wrote:
In that case you don't need a lambda:

import Tkinter as tk

class Test:
def __init__(self, parent):
buttons = [tk.Button(parent, text=str(x+1),
command=self.highlight(x)) for x in range(5)]
for button in buttons:
button.pack(side=tk.LEFT)
Well, actually, that's wrong. You obviously don't understand why lambda
is necessary for event binding; in this case (and many others, for that
matter), the button gets bound to the event *returned* by
self.highlight(x), which, since nothing gets returned, would be None.
Then when you click the button, Tkinter calls None(), and out of the
blue, an error is raised.

Lambda is the safe way around that error.

def highlight(self, x):
print "highlight", x

root = tk.Tk()
d = Test(root)
root.mainloop()

Bye,
bearophile
Sep 16 '06 #6
Dustan wrote:
Jay wrote:
>>Thanks for the tip, but that breaks things later for what I'm doing.

be************@lycos.com wrote:
>>>In that case you don't need a lambda:

import Tkinter as tk

class Test:
def __init__(self, parent):
buttons = [tk.Button(parent, text=str(x+1),
command=self.highlight(x)) for x in range(5)]
for button in buttons:
button.pack(side=tk.LEFT)


Well, actually, that's wrong. You obviously don't understand why lambda
is necessary for event binding; in this case (and many others, for that
matter), the button gets bound to the event *returned* by
self.highlight(x), which, since nothing gets returned, would be None.
Then when you click the button, Tkinter calls None(), and out of the
blue, an error is raised.

Lambda is the safe way around that error.

>> def highlight(self, x):
print "highlight", x

root = tk.Tk()
d = Test(root)
root.mainloop()

Bye,
bearophile

Actually, lambda is not necessary for event binding, but a closure (if I
have the vocab correct), is:

import Tkinter as tk

def make_it(x):
def highliter(x=x):
print "highlight", x
return highliter

class Test:
def __init__(self, parent):
buttons = [tk.Button(parent, text=str(x+1),
command=make_it(x)) for x in range(5)]
for button in buttons:
button.pack(side=tk.LEFT)

root = tk.Tk()
d = Test(root)
root.mainloop()
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Sep 16 '06 #7
James Stroud <js*****@mbi.ucla.eduwrites:
Actually, lambda is not necessary for event binding, but a closure (if
I have the vocab correct), is: ...

def make_it(x):
def highliter(x=x):
print "highlight", x
return highliter
For that version you shouldn't need the x=x:

def make_it(x):
def highliter():
print "highlight", x
return highliter

The reason is each time you call make_it, you're creating a new scope
where x has the correct value, and highliter keeps referring to that
scope even after make_it has returned.
Sep 16 '06 #8

James Stroud wrote:
Dustan wrote:
Jay wrote:
>Thanks for the tip, but that breaks things later for what I'm doing.

be************@lycos.com wrote:

In that case you don't need a lambda:

import Tkinter as tk

class Test:
def __init__(self, parent):
buttons = [tk.Button(parent, text=str(x+1),
command=self.highlight(x)) for x in range(5)]
for button in buttons:
button.pack(side=tk.LEFT)

Well, actually, that's wrong. You obviously don't understand why lambda
is necessary for event binding; in this case (and many others, for that
matter), the button gets bound to the event *returned* by
self.highlight(x), which, since nothing gets returned, would be None.
Then when you click the button, Tkinter calls None(), and out of the
blue, an error is raised.

Lambda is the safe way around that error.

> def highlight(self, x):
print "highlight", x

root = tk.Tk()
d = Test(root)
root.mainloop()

Bye,
bearophile

Actually, lambda is not necessary for event binding, but a closure (if I
have the vocab correct), is:
Of course. What I should have said was "lambda is the quickest and
easiest way". However, if you want your intent to be clear, lambda
isn't always the best option, but it is quite often the quickest.
>
import Tkinter as tk

def make_it(x):
def highliter(x=x):
print "highlight", x
return highliter

class Test:
def __init__(self, parent):
buttons = [tk.Button(parent, text=str(x+1),
command=make_it(x)) for x in range(5)]
for button in buttons:
button.pack(side=tk.LEFT)

root = tk.Tk()
d = Test(root)
root.mainloop()
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Sep 16 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Burt Leavenworth | last post by:
Have used TKINTER for years with Python v1.5.2 with great success. But after installing verson 2.0 (and most recently 2.2.3) I have a problem exiting widgets by clicking on the exit button (x on...
2
by: mksql | last post by:
New to Tkinter. Initially, I had some code that was executing button commands at creation, rather than waiting for user action. Some research here gave me a solution, but I am not sure why the...
2
by: Paul A. Wilson | last post by:
I'm new to Tkinter programming and am having trouble creating a reusable button bar... I want to be able to feed my class a dictionary of button names and function names, which the class will make....
1
by: Ajay | last post by:
hi! if i set two buttons to call the same function when they are pressed, is there any way, within the function of knowing which button invoked it. cheers -- Ajay Brar, CS Honours 2004
14
by: frizzle | last post by:
Hi there, I have a form on a contact page, and to make the layout cross-browser/-platform i want to use an image as a button instead of using an image as background on a button.... Problem:...
0
by: Daniel Roth | last post by:
Solution to the Back button problem for IE 5.5 and above. 1) Get rid of the cache Response.CacheControl = "no-cache"; Response.AddHeader("Pragma", "no-cache"); 2) set SmartNavigation = true...
2
by: Andrew Trevorrow | last post by:
Our app uses embedded Python to allow users to run arbitrary scripts. Scripts that import Tkinter run fine on Windows, but on Mac OS X there is a serious problem. After a script does "root = Tk()"...
4
by: Davy | last post by:
Hi all, I have written a simple Tkinter program, that is draw a rectangle in a canvas, when I press Up key, the rectangle move up. But the program seems work not properly? My environment is...
1
by: Francesco Bochicchio | last post by:
Il Mon, 18 Aug 2008 12:15:10 +0100, dudeja.rajat ha scritto: Uhm, I don't think you should use the grid manager to obtain a window like that. The grid manager is for equally distributing...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.