【发布时间】:2025-12-29 15:50:12
【问题描述】:
我正在尝试为围棋游戏的虚拟棋盘创建 GUI。应该有一个nxn 格子网格,玩家可以在其中放置黑色或白色的石头。单击图块将使其从棕褐色(默认)变为黑色,再次单击变为白色,然后单击第三次返回棕褐色。玩家一可以在一个地方点击一次以放置一块石头,玩家二可以点击两次(您需要稍后移除石头,所以点击三下会重置它)。我创建了一个 tile 对象,然后使用嵌套的 for 循环来实例化其中的 9 x 9。不幸的是,运行代码似乎只产生 1 个功能块,而不是 81 个。这段代码应该可以在任何 python 机器上运行(我使用的是 Python 3.4),所以你可以尝试运行它并亲自查看。谁能指出循环只运行一次的原因?
from tkinter import *
window = Tk()
n = 9
"""
A tile is a point on a game board where black or white pieces can be placed. If there are no pieces, it remains tan.
The basic feature is the "core" field which is a tkinter button. when the color is changed, the button is configured to represent this.
"""
class tile(object):
core = Button(window, height = 2, width = 3, bg = "#F4C364")
def __init__(self):
pass
"""the cycle function makes the tile object actually change color, going between three options: black, white, or tan."""
def cycle(self):
color = self.core.cget("bg")
if(color == "#F4C364"): #tan, the inital value.
self.core.config(bg = "#111111")#white.
elif (color == "#111111"):
self.core.config(bg = "#DDDDDD")#black.
else:
self.core.config(bg = "#F4C364")#back to tan.
board = [] #create overall array
for x in range(n):
board.append([])#add subarrays inside it
for y in range(n):
board[x].append(tile())#add a tile n times in each of the n subarrays
T = board[x][y] #for clarity, T means tile
T.core.config(command = lambda: T.cycle()) #I do this now because cycle hadn't been defined yet when I created the "core" field
T.core.grid(row = x, column = y) #put them into tkinter.
window.mainloop()
【问题讨论】:
-
您的命令功能将无法正常工作:它只会循环最后一个按钮。您可以轻松解决此问题:
command = lambda t=T: t.cycle()。但是还有更好的方法;我会尽快发布答案。
标签: python arrays object button tkinter