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()
Asked By: rakahari

||

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()
Answered By: Novel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.