soham
soham

Reputation: 28

How to determine which button is clicked in tkinter

I am trying to make a software but the problem is when I click the button in below code it always shows 9 as output. can anyone suggest solution for this.

from tkinter import *

root = Tk()

frame = Frame(root)

def click(i):
  print(i)

for i in range(10):
    btn = Button(frame,text="Button",command=lambda: click(i))
    btn.pack(...)

root.mainloop()    

Upvotes: 1

Views: 184

Answers (1)

Novel
Novel

Reputation: 13729

You need to use a partial object:

from functools import partial

for i in range(10):
    btn = Button(frame,text="Button",command=partial(click, i))

Or a lambda function default value:

for i in range(10):
    btn = Button(frame,text="Button",command=lambda i=i: click(i))

Upvotes: 1

Related Questions