我正在嘗試使用 Tkinter 在 Python 中創建一個基本的戰艦游戲。
下面是我的代碼的一個非常簡化的版本。本質上,我正在創建一個 10*10 的按鈕網格并使用.grid. 我想要做的是單擊這些按鈕之一并將該按鈕網格值 (x, y) 從GameBoard類傳遞到Battleship類以定位船舶。
我曾嘗試使用self.row = rowand 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()
uj5u.com熱心網友回復:
正如@ acw1668在評論中指出,問題是gboard屬性row和column當你呼叫還沒有被創建bt.position_ship()的main()功能。
我不知道你的整體游戲設計,但一個非常簡單的解決GameBoard.__init__()方法是在方法中為它們分配一個隨機的棋盤位置。
我還修改了代碼以顯示bt.position_ship()單擊按鈕時如何呼叫。這是通過將BattleShip實體傳遞bt給build_grid()函式來完成的,因此它可以包含在對clicked()方法的呼叫中,現在可以在呼叫時呼叫它。
from random import randrange
import tkinter as tk
class GameBoard:
def __init__(self):
self.mw = tk.Tk()
self.size = 10
self.row = randrange(self.size)
self.column = randrange(self.size)
def build_grid(self, bt):
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(bt, row, column))
self.button.grid(row=x, column=y)
def clicked(self, bt, row, column):
print(row, column)
self.row = row
self.column = column
bt.position_ship()
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()
bt = Battleship(gboard)
gboard.build_grid(bt)
bt.position_ship()
tk.mainloop()
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383486.html
