使用2d数组创建可点击的TKinter画布

时间:2014-11-18 06:44:25

标签: python canvas tkinter

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

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()

2 个答案:

答案 0 :(得分:1)

您可以在点击时在画布上放置彩色矩形,并在再次单击时将其删除:

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()

答案 1 :(得分:0)

尝试循环遍历列表,并使用每个条目将Button-1事件绑定到画布对象,因此:

self.board = list([list(range(5)), list(range(5)), list(range(5)), list(range(5)), list(range(5))])
for x in range(0, 5, 1):
    for y in range(0, 5, 1):
         self.board[x][y] = Canvas(<your settings>)
         self.board[x][y].grid(row = x, column = y)
         self.board[x][y].bind('<Button-1>', <your click event>)

这应该很适合你。