Reputation: 23
I'm currently making a GUI with TkInter, the GUI is made of a grid built in a for loop, with 1 variable for all buttons(It gets updated on every loop). I would like to know how I could get the coordinates of any button that i'd press. (For example, When I press, the button gives it's coordinates on the grid) I used grid_info but it only gets the info of the last button created. Thanks for helping me :)
Upvotes: 0
Views: 6837
Reputation: 385870
You can pass the row and column to the command associated with the function. The two most common ways to do that are with lambda, or with functools.partial.
Here's an example using lambda:
import tkinter as tk
def click(row, col):
label.configure(text="you clicked row %s column %s" % (row, col))
root = tk.Tk()
for row in range(10):
for col in range(10):
button = tk.Button(root, text="%s,%s" % (row, col),
command=lambda row=row, col=col: click(row, col))
button.grid(row=row, column=col, sticky="nsew")
label = tk.Label(root, text="")
label.grid(row=10, column=0, columnspan=10, sticky="new")
root.grid_rowconfigure(10, weight=1)
root.grid_columnconfigure(10, weight=1)
root.mainloop()
Upvotes: 2