Problem in python, tkinter module with getting button id

Question:

Hi wanted to get in this program something like getting button id, here is code:

import tkinter as tk
root = tk.Tk()


def button_click(event):
    button = event.widget
    print(button['text'])


buttons = []
k = 0
for x in range(10):
    for y in range(10):
        buttons.append(tk.Button(root, width=4, height=2, text=k))
        buttons[k].grid(row=x, column=y)
        buttons[k].bind('<Button-1>', lambda e: button_click(e))
        k += 1

root.mainloop()

I want to get extacly same result as that program but without putting any text on those buttons.

Asked By: Szefuni0

||

Answers:

Try this

import tkinter as tk
root = tk.Tk()


def button_click(event, btnId):
    print(btnId)


buttons = []
k = 0
for x in range(10):
    for y in range(10):
        buttons.append(tk.Button(root, width=4, height=2))
        buttons[k].grid(row=x, column=y)
        buttons[k].bind('<Button-1>', lambda e, btnId=k: button_click(e, btnId))
        k += 1

root.mainloop()

Don’t use text=k instead add a parameter in button_click and pass k as a parameter.

Answered By: codester_09
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.