-4

I want to have UI where when I press a button, stuff pops up in the console. The issue is the stuff prints into the console before I press the button. After some testing, I have found that if I don't use parenthesis to call my function in the command argument, it works fine.

ex: A function called hello prints hello world in the console, so I would call it like button=Button(master, command=hello) instead of button=Button(master, command=hello())

The issue with this way is I can't use parameters.

here is an example of a code similar to mine:

index={'Food':['apple', 'orange'], 'Drink':['juice', 'water', 'soda']}
Names=['Food', 'Drink']

def display(list):
    for item in list:
        print(item)

from tkinter import *
mon=Tk()
app=Frame(mon)
app.grid()

for item in Names:
    button=Button(mon, text=item, command=diplay(index[item]))
    button.grid()
mon.mainloop()

Any ideas of how to be able to use parameters? I hope this all made sense, but if it didn't please leave a comment. Thank You.

1
  • Did you try pasting your question's title into a Google search? Commented Jun 18, 2015 at 19:12

1 Answer 1

3

You are looking for the lambda keyword:

from tkinter import *
index={'Food':['apple', 'orange'], 'Drink':['juice', 'water', 'soda']}
Names=['Food', 'Drink']

def display(list):
    for item in list:
        print(item)

mon=Tk()
app=Frame(mon)
app.grid()

for item in Names:
    Button(mon, text=item, command= lambda name = item: display(index[name])).grid()
mon.mainloop()

You have to use name = item so that every time a button is initialized, it takes the current value of item from the for loop.

If for example you used lambda: display(index[item]), both buttons would display the values for 'Drink' because that is the last value of the lambda function initialized in the loop.

Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou, instead of marking it as duplicate like the rest

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.