如何在python tkinter中创建响应式网格?

xcitsw88  于 2023-02-26  发布在  Python
关注(0)|答案(1)|浏览(110)

我尝试在tkinter中创建一个彩色网格,这样当我点击网格的任何特定部分时,它就会改变颜色。
下面的代码是网格外观的一个示例-

密码-

def draw_board(canvas):
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            x0, y0 = i * SQUARE_SIZE, j * SQUARE_SIZE
            x1, y1 = x0 + SQUARE_SIZE, y0 + SQUARE_SIZE
            color_grid = [[random.choice(COLORS) for j in range(GRID_SIZE)] for i in range(GRID_SIZE)] # COLORS = ["green", "yellow"]
            canvas.create_rectangle(x0, y0, x1, y1, fill=color_grid[i][j])

任何帮助都将不胜感激。

92vpleto

92vpleto1#

可以使用tag_bind()将事件处理程序绑定到给定的Canvas项,如下所示

def on_click(event):  # event handler function
    item = canvas.find_closest(event.x, event.y)
    canvas.itemconfig(item, fill='#FF3344')  # set new fill color

def draw_board(canvas):
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            x0, y0 = i * SQUARE_SIZE, j * SQUARE_SIZE
            x1, y1 = x0 + SQUARE_SIZE, y0 + SQUARE_SIZE
            color_grid = [[random.choice(COLORS) for j in range(GRID_SIZE)] for i in range(GRID_SIZE)] # COLORS = ["green", "yellow"]
            rect = canvas.create_rectangle(x0, y0, x1, y1, fill=color_grid[i][j])
            canvas.tag_bind(rect, '<Button>', on_click)  # bind the event handler function

相关问题