Okay, the problem Im having is that I do not understand how to refer to that particular button that was pressed. Im doing a game, if the use clicks a button I wanna know which X and Y coordinate it had. So, if you have a grid of buttons and you click one I want the coordinates and then I will change that button’s color. 🙂
PROBLEM: Knowing which button was pressed in a grid.
Thanks in advance!
def matris():
for i in range(5):
newButton = Button(app, width = 4, height = 2, bg = "blue",command = lambda i=i: function(i))
newButton.grid(row = i, column = 0)
for i in range(5):
newButton = Button(app, width = 4, height = 2, bg = "blue",command = lambda i=i + 5: function(i))
newButton.grid(row = i, column = 1)
for i in range(5):
newButton = Button(app, width = 4, height = 2, bg = "blue",command = lambda i=i + 10: function(i))
newButton.grid(row = i, column = 2)
for i in range(5):
newButton = Button(app, width = 4, height = 2, bg = "blue",command = lambda i=i + 15: function(i))
newButton.grid(row = i, column = 3)
for i in range(5):
newButton = Button(app, width = 4, height = 2, bg = "blue",command = lambda i=i + 20: function(i))
newButton.grid(row = i, column = 4)
def function(i):
if button 23 was clicked.changeColor to e.g "blue"
After reading all the comments and edits, it looks like what you really want to know is “which button was clicked?” when using the same command for multiple buttons.
The easiest way to do that is to pass some sort of unique identifier to the command associated with the widget. The most straight-forward way is to pass a reference to the widget itself, though that requires a two step process.
For example:
You can also use
functools.partialto get the same result if you find lambda hard to wrap your head around:If you prefer to create your button in a single step instead of two, you need some way to identify it. For me, the easiest way is with a dictionary. For example, if you’re creating rows and columns of buttons, you could do this: