python - How to have parameters to a button command in tkinter python3 -
this question has answer here:
i want have ui when press button, stuff pops in console. issue stuff prints console before press button. after testing, have found if don't use parenthesis call function in command
argument, works fine.
ex: function called hello
prints hello world in console, call button=button(master, command=hello)
instead of button=button(master, command=hello())
the issue way can't use parameters.
here example of code similar mine:
index={'food':['apple', 'orange'], 'drink':['juice', 'water', 'soda']} names=['food', 'drink'] def display(list): item in list: print(item) tkinter import * mon=tk() app=frame(mon) app.grid() item in names: button=button(mon, text=item, command=diplay(index[item])) button.grid() mon.mainloop()
any ideas of how able use parameters? hope made sense, if didn't please leave comment. thank you.
you looking lambda
keyword:
from tkinter import * index={'food':['apple', 'orange'], 'drink':['juice', 'water', 'soda']} names=['food', 'drink'] def display(list): item in list: print(item) mon=tk() app=frame(mon) app.grid() item in names: button(mon, text=item, command= lambda name = item: display(index[name])).grid() mon.mainloop()
you have use name = item every time button initialized, takes current value of item
loop.
if example used lambda: display(index[item])
, both buttons display values 'drink'
because last value of lambda function initialized in loop.
Comments
Post a Comment