Hi all

I've been messing about with this bit of code. Basically what it's
supposed to do is create these six buttons, which when clicked pass a parameter to a function and then call that function. The function basically removes one condition from a larger list depending on which button is clicked The problem is that the way I've written it, the functions runs automatically before the user actually clicks the button.

firstCond = ''
condNames = ['1', '2', '3', '4',  '5', '6']
for item in condNames:
    button = Button(frame, name = str(item), text = str(item), command = getCond(item)).pack()
def getCond(par):
    firstCond = par
    conditions.remove(firstCond)
    print firstCond
    print conditions

So I want the function to run when the button is clicked, not automatically on its own. Now I know that the reason it does this is because of the brackets following getCond(item). However, I cannot see any other way of passing the parameter to the function.

Obviously, I could make separate functions for each condition, but I'm just wondering if I could do it more elegantly in this way? It would be a pain if I had 100 conditions instead of 6...

Recommended Answers

All 5 Replies

Here is an example how to use lambda to pass arguments in Tkinter's button command:

import Tkinter as tk

def getCond(par):
    firstCond = par
    #conditions.remove(firstCond)
    print firstCond
    #print conditions


root = tk.Tk()

firstCond = ''

condNames = ['1', '2', '3', '4',  '5', '6']
for item in condNames:
    # use lambda to pass arguments to command-function
    tk.Button(root, text=str(item), command=lambda i=item: getCond(i)).pack()

root.mainloop()

Also, create your function before you call it.

commented: Perfect answer +0

Hi friends,
i am happy with above code. Can u please explain easily about lambda command plz..

An example might explain it better ...

# normal function declaration
def timestwo1(x):
  return x * 2

# using lambda (not anonymous)
timestwo2 = lambda x: x * 2

# test it ...
print(timestwo1(4))  # 8
print(timestwo2(4))  # 8

# or make it anonymous ('on the fly')
print((lambda x: x * 2)(4))  # 8
commented: A great example. It's worth pointing out that the two functions timetwo1 and timetwo2 are identical. xxx = lambda ... is a perfectly valid way to create a function. Indeed in some languages it is the way it's done. +0

Thank u very much sir i got clearly understood from your explanation

Lambda was introduced to Python from Lisp and allows for easier functional programming.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.