Я пытаюсь запрограммировать игру тральщика на python, используя tkinter. Я начал с создания сетки кнопок, используя двумерный список, генерацию кнопки и все работает. Единственная проблема, с которой я столкнулся, это то, что я не знаю, как определить, какая кнопка в моей сетке нажата. Моя цель состоит в том, чтобы иметь возможность нажимать на кнопку, и благодаря этому я знаю координаты этого в моей сетке [строка] [столбец].
Это код, который у меня есть.
from tkinter import *
from functools import partial
from itertools import product
# Here, we are creating our class, Window, and inheriting from the Frame
# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
class Window(Frame):
# Define settings upon initialization. Here you can specify
def __init__(self, master=None):
# parameters that you want to send through the Frame class.
Frame.__init__(self, master)
#reference to the master widget, which is the tk window
self.master = master
#with that, we want to then run init_window, which doesn't yet exist
numRows = int(input("# of Rows: "))
numCols = int(input("# of Cols: "))
self.init_window(numRows, numCols)
#Creation of init_window
def init_window(self, rowNum, colNum):
# print(x, y)
# changing the title of our master widget
self.master.title("GUI")
# allowing the widget to take the full space of the root window
self.pack(fill=BOTH, expand=1)
# creating a button instance
#quitButton = Button(self, text="Exit",command=self.client_exit)
# placing the button on my window
#quitButton.place(x=0, y=0)
but = []
for row in range(0, rowNum):
curRow = []
for col in range(0, colNum):
curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))
curRow[col].grid(row=row,column=col)
but.append(curRow)
#but[1][1].config(state="disabled")
#but[1][1]["text"] = "3"
#but[1][1]["bg"] = "white"
def open_button(self, r, c):
print(r, " : ", c)
# root window created. Here, that would be the only window, but
# you can later have windows within windows.
root = Tk()
root.geometry("600x600")
#creation of an instance
app = Window(root)
#mainloop
root.mainloop()
Всякий раз, когда я нажимаю на сетку, она дает мне самую последнюю кнопку ...
Например, сетка 9x9 всегда дает мне «9: 9» всякий раз, когда я нажимаю любую кнопку.
Решения приветствуются! Я хочу простой способ получить координаты, не меняя слишком много кода (если это возможно).
Спасибо!