0

Using tkinter, I would like to create a graphical user interface (gui) with multiple buttons that perform an action depending on the index of the button. The problem I face is that all buttons are assigned to the last function that I define, and not the the one that I assigned iteratively to the button in the code.

Here is a simple code-example that illustrates my issue.

from tkinter import *

window = Tk()
r = 1
links = []
y = []
for n in range(10):
    links.append(Button(window, text='button '+str(n), cursor='hand2'))
    links[n].grid(row=r, column=3, sticky=W)
    y.append(lambda x: print('This is the Button number ' + str(n)))
    links[n].bind('<Button-1>', y[n])
    r += 1
window.mainloop()

Running this script opens a gui with 10 buttons.

Clicking on any button will print This is the Button number 9 (the last button). However, I would like that upon clicking button n, it will print This is the Button number n . Any ideas how to achieve this?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Felix
  • 1
  • 1

0 Answers0