I have a 3x3 grid of buttons, all of which are bound to the same event funciton. This function changes the labels of particular buttons, based on which button was clicked. I want to be able to choose which buttons will be effected by looking at where they fall on the grid, ie row and column values.
For example, I want to be able to say "considering the button clicked was on (row 1, column 2), I want to change the labels of the buttons on (row 2, column 0) and (row 1, column 1).
I know how to find the row and column of the button which was clicked:
import tkinter
def click(event):
space = event.widget
space_label = space['text']
row = space.grid_info()['row'] #get the row of clicked button
column = space.grid_info()['column'] #get the column of clicked button
board = tkinter.Tk()
for i in range(0,9): #creates the 3x3 grid of buttons
button = tkinter.Button(text = "0")
if i in range(0,3):
r = 0
elif i in range(3,6):
r = 1
else:
r = 2
button.grid(row = r, column = i%3)
button.bind("<Button-1>",click)
board.mainloop()
But I can't figure out how to access a button's label given only a row and column of the grid.
PS new to coding, sorry if this is obvious, i looked around but couldn't find any similar enough questions.
If you plan to do anything with a widget after creating it and adding it to your interface, it's a good idea to keep a reference.
Here is a modification of your code that creates a dictionary button_dict
to store each of your buttons. The keys are tuples (row,column)
. I added the button_dict
as an additional input to your click
function and modified the button binding to include this new input using lambda
.
import tkinter
def click(event,button_dict):
space = event.widget
space_label = space['text']
row = space.grid_info()['row'] #get the row of clicked button
column = space.grid_info()['column'] #get the column of clicked button
button = button_dict[(row,column)] # Retrieve our button using the row/col
print(button['text']) # Print button text for demonstration
board = tkinter.Tk()
button_dict = {} # Store your button references here
for i in range(0,9): #creates the 3x3 grid of buttons
button = tkinter.Button(text = i) # Changed the text for demonstration
if i in range(0,3):
r = 0
elif i in range(3,6):
r = 1
else:
r = 2
button.grid(row = r, column = i%3)
button.bind("<Button-1>",lambda event: click(event,button_dict))
button_dict[(r,i%3)] = button # Add reference to your button dictionary
board.mainloop()
If you were only interested in the button that was pressed, you can simply access the event.widget
attribute. From your example, it sounds like you want to modify any number of buttons on each event so I think the dictionary will give you more versatility.
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.