Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter - Same event for multiple buttons

Tags:

events

tkinter

Using Tkinter, I have many buttons. I would like the same callback function to be triggered every time any of the buttons pressed. How can I find out which button was pressed ?

def call(p1):
    # Which Button was pressed?
    pass

for i in range (50):
    B1 = Button(master, text = '...', width = 2)
    B1.grid(row = i*20, column = 60)               
    B1.bind('<Button-1>',call)

    B2 = Button(master, text = '...', width = 2)
    B2.grid(row = i*20, column = 60)               
    B2.bind('<Button-1>',call)
like image 314
user1530405 Avatar asked Nov 14 '25 18:11

user1530405


1 Answers

Using a list to reference the dynamically created buttons and lambda to store a reference to the index of the button object. You can determine which button was clicked. In the below examples I use .cget("text") on the button object to demonstrate accessing the button widget.

import tkinter as tk

root = tk.Tk()
root.minsize(200, 200)

btn_list = [] # List to hold the button objects

def on_click(idx):
    print(idx) # Print the index value
    print(btn_list[idx].cget("text")) #Print the text for the selected button

for i in range(10):
    # Lambda command to hold reference to the index matched with range value
    b = tk.Button(root, text = f'Button #{i}', command = lambda idx = i: on_click(idx))
    b.grid(row = i, column = 0)

    btn_list.append(b) # Append the button to a list

root.mainloop()

Alternatively you can use bind and then access the widget from the event object generated.

import tkinter as tk
    
root = tk.Tk()
root.minsize(200, 200)

def on_click(event):
    btn = event.widget # event.widget is the widget that called the event
    print(btn.cget("text")) #Print the text for the selected button

for i in range(10):
    b = tk.Button(root, text = f'Button #{i}')
    b.grid(row = i, column = 0)
    # Bind to left click which generates an event object
    b.bind("<Button-1>", on_click)

root.mainloop()
like image 112
Steven Summers Avatar answered Nov 17 '25 08:11

Steven Summers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!