我很擅长编码并试图用Python制作一个井字游戏。 到目前为止,它工作正常,但我无法使按钮改变颜色。
我希望按钮在Cells[]
之后查看move()
的bg颜色。
也许我从这开始就错了。但现在我一无所知。
我无法找到任何我设法按照自己的意愿工作的刷新功能。
from tkinter import *
class Board:
def __init__(self):
self.root =Tk()
self.root.minsize(300,300)
self.cells = ["", "white", "white", "white",
"white", "white", "white",
"white", "white", "white"]
self.count = 0 #keeping count of next color
#Player makes a move:
def move(self, cell_coice):
x = cell_coice
if self.count == 0:
if self.cells[x] == "white":
self.cells[x] = "red"
print (self.cells) #remove
self.count = 1
else:
self.count = 1
print (self.cells) #remove
else:
if self.cells[x] == "white":
self.cells[x] = "blue"
print (self.cells) #remove
self.count = 0
else:
self.coint = 0
print (self.cells) #remove
def buttons(self):
b1 = Button(self.root, bg=self.cells[1], command=lambda:self.move(1))
b1.grid(row=1, column=1, sticky=NSEW)
b2 = Button(self.root, bg=self.cells[2], command=lambda:self.move(2))
b2.grid(row=1, column=2, sticky=NSEW)
b3 = Button(self.root, bg=self.cells[3], command=lambda:self.move(3))
b3.grid(row=1, column=3, sticky=NSEW)
b4 = Button(self.root, bg=self.cells[4], command=lambda:self.move(4))
b4.grid(row=2 , column=1, sticky=NSEW)
b5 = Button(self.root, bg=self.cells[5], command=lambda:self.move(5))
b5.grid(row=2 , column=2, sticky=NSEW)
b6 = Button(self.root, bg=self.cells[6], command=lambda:self.move(6))
b6.grid(row=2 , column=3, sticky=NSEW)
b7 = Button(self.root, bg=self.cells[7], command=lambda:self.move(7))
b7.grid(row=3, column=1, sticky=NSEW)
b8 = Button(self.root, bg=self.cells[8], command=lambda:self.move(8))
b8.grid(row=3, column=2, sticky=NSEW)
b9 = Button(self.root, bg=self.cells[9], command=lambda:self.move(9))
b9.grid(row=3, column=3, sticky=NSEW)
Grid.rowconfigure(self.root, 1, weight=1)
Grid.columnconfigure(self.root, 1, weight=1)
Grid.rowconfigure(self.root, 2, weight=1)
Grid.columnconfigure(self.root, 2, weight=1)
Grid.rowconfigure(self.root, 3, weight=1)
Grid.columnconfigure(self.root, 3, weight=1)
OpenBoard = Board()
OpenBoard.buttons()
OpenBoard.root.mainloop()
答案 0 :(得分:0)
要更改按钮的颜色,您需要能够访问按钮对象。这意味着您需要在buttons()
方法中添加一些代码,以将对象保存为实例变量:
self.btns = [Button(), b1, b2, b3, b4, b5, b6, b7, b8, b9]
现在您可以将其添加到move()
方法中以循环显示值和颜色并设置每个颜色:
for btn, color in zip(self.btns, self.cells):
btn.config(bg=color)
请注意,您必须在列表中使用有效颜色作为虚拟颜色,而不是""
。