Home > Mobile >  Problem in python, tkinter module with getting button id
Problem in python, tkinter module with getting button id

Time:12-18

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.

CodePudding user response:

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.

  • Related