我正在尝试使用 Tkinter 在 Python 中创建一个基本的 Battleship 游戏。
下面是我的代码的一个非常简化的版本。本质上,我正在创建一个 10*10 的按钮网格并使用.grid
. 我想做的是单击其中一个按钮并将该按钮的网格值(x,y)从GameBoard
类传递给Battleship
类以定位船。
我试过使用self.row = row
and self.column = column
,但是当我这样做时,我立即收到一个属性错误,'GameBoard' object has no attribute 'row'
.
import tkinter as tk
class GameBoard:
def __init__(self):
self.mw = tk.Tk()
self.size = 10
def build_grid(self):
for x in range(self.size):
for y in range(self.size):
self.button = tk.Button(self.mw, text = '', width = 2, height = 1,\
command = lambda row = x, column = y: self.clicked(row, column))
self.button.grid(row = x, column = y)
def clicked(self, row, column):
print(row, column)
self.row = row
self.column = column
class Battleship:
def __init__(self, board):
self.gboard = board
def position_ship(self):
x = self.gboard.row
y = self.gboard.column
for i in range (3):
self.submarine = tk.Button(self.gboard.mw, background = "black", text = '',\
width = 2, height = 1)
self.submarine.grid(row = x, column = y)
def main():
gboard = GameBoard()
gboard.build_grid()
bt = Battleship(gboard)
bt.position_ship()
main()