【发布时间】:2021-08-25 13:36:33
【问题描述】:
我想根据按钮的行和列更改按钮的颜色。我可以搜索相邻的按钮,但不能对它们做任何事情。代码是棋盘游戏奥赛罗的 python 版本,我试图让游戏的“三明治”方面运行。理想情况下,它保留在网格系统中,以便我能够根据自己的能力编写代码
from tkinter import *
### Function to change button colour ###
def changeColour(tempButton, row, column):
if tempButton.cget("bg") == "black":
tempButton.configure (bg = "white")
else:
tempButton.configure (bg = "black")
sandwichButton(tempButton, row, column)
### Function to sandwich adjacent buttons ###
def sandwichButton(originButton, row, column):
for x in range (-1,2,1):
for y in range (-1,2,1):
aRow = (row + y)
aColumn = (column + x)
adjacentInfo = find_position(othello, aRow, aColumn)
endButtonInfo = find_position(othello, aRow + y, aColumn + x)
if adjacentInfo["row"] == (aRow) and adjacentInfo["column"] == (aColumn):
adjacentButton = ADJACENT INFORMATION
if endButtonInfo["row"] == (aRow + y) and endButtonInfo["column"] == (aColumn+x):
if originButton.cget("bg") == "black":
adjacentButton.configure (bg = "white")
else:
adjacentButton.configure (bg = "black")
### Function to find button position ###
def find_position(frame, row, column):
for children in frame.children.values():
info = children.grid_info()
if info["row"] == row and info["column"] == column:
return info
break
### Creating the window ###
othello = Tk()
othello.title("Othello Draft 1")
othello.geometry("800x800")
### Creating buttons ###
for r in range (8): #Rows
for c in range(8): #Columns
button = Button(othello, width = 10, height = 5)
button.grid(row = r, column = c)
button.configure (bg = "green", command = lambda buttonName = button, r = r, c = c: changeColour(buttonName, r, c))
### Running the window ###
othello.mainloop()
【问题讨论】:
标签: python tkinter button colors grid