Tkinter基于行和列修改按钮

2024-06-13 07:37:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据按钮的行和列更改按钮的颜色。我可以搜索相邻的按钮,但不能用它们做任何事情。代码是桌面游戏Otherlo的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()

Tags: ininfoforifconfigurerangecolumnbutton
1条回答
网友
1楼 · 发布于 2024-06-13 07:37:36

您可以将按钮添加到列表中,并使用if和elif语句来配置按钮并将条件输入if

for button in [list your buttons here]
    if condition:
        button.config(command=command(), bg=colour)
    elif condition:
        button.config(command=command2(), bg=colour2)

相关问题 更多 >