Skip to main content
 首页 » 编程设计

python之使用二维数组创建可点击的 TKinter Canvas

2025年05月04日10yjmyzz

我想创建一个由 5x5 单元格组成的 TKinter Canvas ,您可以在其中单击任何单元格并更改颜色。为了简单起见,我们只处理黑色和白色。我想使用一个 2d 5x5 数组来创建它,该数组从全 0 开始表示全白。当你点击 Canvas 上的一个单元格时,它应该将二维数组上的相应点更改为 1,并将颜色更改为黑色。这是我到目前为止所拥有的。我只是不知道如何在二维数组和 Canvas 之间建立连接。另外,如何使用可点击的单元格填充 Canvas ?

from tkinter import * 
 
class CellArray(): 
    def __init__(self, root): 
        self.board = [[0, 0, 0, 0, 0,] 
                 [0, 0, 0, 0, 0,], 
                 [0, 0, 0, 0, 0,], 
                 [0, 0, 0, 0, 0,], 
                 [0, 0, 0, 0, 0,], 
                 [0, 0, 0, 0, 0,],] 
 
class CellCanvas(Frame): 
    def __init__(self, root): 
        Frame.__init__(self, root) 
        self.initBoard() 
 
    def initBoard(self): 
        self.display = Canvas(root, width=500, height=500, borderwidth=5, background='white') 
        self.display.grid() 
 
root = Tk() 
board = CellCanvas(root) 
root.mainloop() 

请您参考如下方法:

您可以在点击时在 Canvas 上放置彩色矩形,并在再次点击时将其移除:

import Tkinter as tk 
 
# Set number of rows and columns 
ROWS = 5 
COLS = 5 
 
# Create a grid of None to store the references to the tiles 
tiles = [[None for _ in range(COLS)] for _ in range(ROWS)] 
 
def callback(event): 
    # Get rectangle diameters 
    col_width = c.winfo_width()/COLS 
    row_height = c.winfo_height()/ROWS 
    # Calculate column and row number 
    col = event.x//col_width 
    row = event.y//row_height 
    # If the tile is not filled, create a rectangle 
    if not tiles[row][col]: 
        tiles[row][col] = c.create_rectangle(col*col_width, row*row_height, (col+1)*col_width, (row+1)*row_height, fill="black") 
    # If the tile is filled, delete the rectangle and clear the reference 
    else: 
        c.delete(tiles[row][col]) 
        tiles[row][col] = None 
 
# Create the window, a canvas and the mouse click event binding 
root = tk.Tk() 
c = tk.Canvas(root, width=500, height=500, borderwidth=5, background='white') 
c.pack() 
c.bind("<Button-1>", callback) 
 
root.mainloop()