【问题标题】:Tkinter - modifying buttons based on rows and columnsTkinter - 根据行和列修改按钮
【发布时间】: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


    【解决方案1】:

    您可以将按钮添加到列表中并使用 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)
    

    【讨论】:

    • 我遇到的问题是我无法使用相邻按钮执行任何命令,因为我不知道如何选择要引用的按钮,只能选择单击的按钮。是否可以根据其行或列获取按钮?理想情况下是这样的if button[row + 1].cget("bg") == colour:
    • 我现在编辑了,但我忘了补充一点,你的按钮可以列在列表和属性命令中,条件可以是if column < number and column > second number: 这样的东西,以便让他们拥有东西归功于他们。
    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2021-08-04
    • 1970-01-01
    • 2018-02-05
    • 2013-05-07
    • 1970-01-01
    相关资源
    最近更新 更多