简体   繁体   中英

Finding widgets on a grid (tkinter)

Using the tkinter module, suppose I create a grid with 50 button widgets and each of those widgets has different text. I need to be able to specify some way of typing in a row and column so I can get that widget's text at that location.

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.

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

Tkinter store a list of children widgets in the children attribute of a frame. By comparing grid_info() of all children you can find a widget on a given row or column. See find_in_grid function of following example:

from Tkinter import *

root = Tk()

def find_in_grid(frame, row, column):
    for children in frame.children.values():
        info = children.grid_info()
        #note that rows and column numbers are stored as string                                                                         
        if info['row'] == str(row) and info['column'] == str(column):
            return children
    return None

#create an array of button                                                                                                              
width = 10
for i in range(width):
    for j in range(width):
        b = Button(root, text=str(i*width+j))
        b.grid(row=i, column=j)

#Create two entries to set row and column to find. Changing entries print the                                                           
#text of the button (and flash it on compatible platforms)                                                                              
def update(var, value, op):
    r = row.get()
    c = col.get()
    b = find_in_grid(root, r, c)
    if b:
        print "button ({0},{1}) : {2}".format(r, c, b["text"])
        b.flash()

Label(root,text="row:").grid(row=width,column=0)
row = StringVar()
row.trace('w',update)
Entry(root,textvar=row, width=3).grid(row=width,column=1)

Label(root,text="col:").grid(row=width,column=2)
col = StringVar()
col.trace('w',update)
Entry(root,textvar=col, width=3).grid(row=width,column=3)

row.set('3')
col.set('2')

mainloop()

Note: this small example does not handle spanning widgets

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM