5
votes

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

2
Pls clarify, it is difficult to understand what are you asking for. You say that each button widget has a text and that you want that text, and later you say you want info about the grid not about the button... - joaquin

2 Answers

5
votes

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()
1
votes

You got a previous answer relative to a method to save button objects in a dictionary in order to recover them using their (column, row) position in a grid.

So if self.mybuttons is your dictionary of lists of buttons as described in previous answer, then you can get the text at position row, col as this:

abutton = self.mybuttons[arow][acolumn]
text_at_row_col = abutton["text"]

On the other hand, if what you need is to get the text from the button callback:

button.bind("<Button-1>", self.callback)

then you can get the button text from the event, you do not need to know its row/col position, only to press it:

def callback(self, event):
    mybutton = event.widget
    text_at_row_col = mybutton["text"]