Python,tkinter:如何识别网格中项目的位置?

时间:2017-01-15 13:18:48

标签: python tkinter

好的,所以我有这个代码会在tkinter窗口中生成一个按钮网格,但是我没办法分开网格中的按钮。如果我想让按钮处于网格位置(4,4)蓝色,我该怎么做?我需要使用列表吗?我确信这是一个快速修复,提前谢谢。

def game(width,height):

    for x in range(width):

        for y in range(height):

            square = Button(gameWindow)
            square.grid(column = x, row = (y + 1), sticky = (N+S+E+W))

    for x in range(width):

        Grid.columnconfigure(gameWindow, x, weight = 1)

    for y in range(height):

        Grid.rowconfigure(gameWindow, (y + 1), weight = 1)

    gameWindow.mainloop()

game(8,8)

2 个答案:

答案 0 :(得分:0)

square个对象放在列表列表中,然后您可以通过xy

的索引引用每个对象
from Tkinter import *

def game(width,height):
    for x in range(width):
        # fill a row in the list
        squares.append([None] * height)

        for y in range(height):
            squares[-1][y] = Button(gameWindow)
            squares[-1][y].grid(column = x, row = (y + 1), sticky = (N+S+E+W))

    for x in range(width):

        Grid.columnconfigure(gameWindow, x, weight = 1)

    for y in range(height):

        Grid.rowconfigure(gameWindow, (y + 1), weight = 1)

squares = []
gameWindow = Tk()

game(8,8)

# change color of square in x=3, y=4
squares[3][4].configure(bg='blue')

gameWindow.mainloop()

答案 1 :(得分:0)

<强>建议: 如果您正在考虑在视觉上区分网格,除了mike.k的建议之外,您还可以使用Button的背景,activebackground和图像选项。 activebackground选项在鼠标指针所在位置提供对比,并且易于实现。此外,您可以设计一个聪明的系统来显示与网格系统相关的颜色。

修改您的代码以进行演示实施:

x

代码结果enter image description here