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. 8 8126
"Jay" <ja*******@gmai l.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.
Perfect. Thanks.
Paul Rubin wrote:
"Jay" <ja*******@gmai l.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.
In that case you don't need a lambda:
import Tkinter as tk
class Test:
def __init__(self, parent):
buttons = [tk.Button(paren t, text=str(x+1),
command=self.hi ghlight(x)) for x in range(5)]
for button in buttons:
button.pack(sid e=tk.LEFT)
def highlight(self, x):
print "highlight" , x
root = tk.Tk()
d = Test(root)
root.mainloop()
Bye,
bearophile
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(paren t, text=str(x+1),
command=self.hi ghlight(x)) for x in range(5)]
for button in buttons:
button.pack(sid e=tk.LEFT)
def highlight(self, x):
print "highlight" , x
root = tk.Tk()
d = Test(root)
root.mainloop()
Bye,
bearophile
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(paren t, text=str(x+1),
command=self.hi ghlight(x)) for x in range(5)]
for button in buttons:
button.pack(sid e=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
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(paren t, text=str(x+1), command=self .highlight(x)) for x in range(5)] for button in buttons: button.pack(sid e=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.mainloo p()
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(paren t, text=str(x+1),
command=make_it (x)) for x in range(5)]
for button in buttons:
button.pack(sid e=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/
James Stroud <js*****@mbi.uc la.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.
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(paren t, text=str(x+1), command=self. highlight(x)) for x in range(5)] for button in buttons: button.pack(sid e=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(paren t, text=str(x+1),
command=make_it (x)) for x in range(5)]
for button in buttons:
button.pack(sid e=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/ This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 upper right ---
)---the system hangs. It's driving me nuts. Can some kind soul
indicate what PATH statement they're using which deals with
TCL/TK, etc?
Burt Leavenworth.
|
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 extra step is necessary.
This causes the "graph" function to execute when the button is created:
Button(root, text='OK', command=graph(canvas)))
However, this waits until the button is pressed (the desired behavior):
def doit():
graph(canvas)
|
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.
My button bar is implemented a Frame subclass, which takes the button
dictionary as an argument and displays the buttons on the screen:
class OptionsBar(Frame):
def __init__(self, buttonDict, parent=None)
Frame.__init__(self, parent)
|
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
|
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: When i insert a (e.g.) reset-button, and change the source
type="button" to type="image", instead of resetting the form, it
submits the form....
| |
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
Daniel Roth
|
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()" our app's menus
are permanently changed in the following way:
- The top item in the application menu changes to "About Tcl & Tk...".
- The Quit item is disabled.
- The File and Edit menus are completely replaced.
- All further menus (except...
|
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 Python2.5+PythonWin.
##----------------------
from Tkinter import *
class MyApp:
|
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 widgets both
horizontally and vertically.
And I'm not sure that you can realize that window look with Tkinter.
You could get close by horizontally packing each widget row in a frame
and then vertically packing the frames in the window. But the look...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |