Python – finding widgets on a grid (tkinter module)

pythontkinterwidget

Using the tkinter module, suppose I create a grid with 50 button widgets and each of those widgets have different text. I need to be able to specify some way of typing in a row and column and I can get that widget's text at that location. So for example, if I need the widget's text at the third row in the second column of the grid. I've searched the docs but that tells me how to get info about widgets, when I need info about the grid.

Thanks in advance

Best Answer

There's no need to create your own function or keep a list/dictionary, tkinter already has a built-in grid_slaves() method. It can be used as frame.grid_slaves(row=some_row, column=some_column)

Here's an example with a grid of buttons showing how grid_slaves() retrieves the widget, as well as displaying the text.

import tkinter as tk
root = tk.Tk()

# Show grid_slaves() in action
def printOnClick(r, c):
    widget = root.grid_slaves(row=r, column=c)[0]
    print(widget, widget['text'])

# Make some array of buttons
for r in range(5):
    for c in range(5):
        btn = tk.Button(root, text='{} {}'.format(r, c),
                        command=lambda r=r, c=c: printOnClick(r, c))
        btn.grid(row=r, column=c)

tk.mainloop()