How to assign variables to tkinter buttons, to pass to a function
Question:
I am building a script in tkinter that will have an unknown number of buttons, generated from a list. I would like these buttons to pass the list item that created it to a function. In my code below, all buttons pass the same (last) list item. Can anyone please help me get this to work?
from tkinter import *
root = Tk()
def grid_cycle(b):
print(b)
items = [6,3,5,4]
for x in items:
Button(root, text="x", command=lambda *args: grid_cycle(x)).pack()
root.mainloop()
Answers:
One way is to use the partial function (my recommendation):
from functools import partial
for x in items:
Button(root, text=x, command=partial(grid_cycle, x)).pack()
Another common way is to abuse the default arguments for lambda:
for x in items:
Button(root, text=x, command=lambda x=x: grid_cycle(x)).pack()
I am building a script in tkinter that will have an unknown number of buttons, generated from a list. I would like these buttons to pass the list item that created it to a function. In my code below, all buttons pass the same (last) list item. Can anyone please help me get this to work?
from tkinter import *
root = Tk()
def grid_cycle(b):
print(b)
items = [6,3,5,4]
for x in items:
Button(root, text="x", command=lambda *args: grid_cycle(x)).pack()
root.mainloop()
One way is to use the partial function (my recommendation):
from functools import partial
for x in items:
Button(root, text=x, command=partial(grid_cycle, x)).pack()
Another common way is to abuse the default arguments for lambda:
for x in items:
Button(root, text=x, command=lambda x=x: grid_cycle(x)).pack()