繁体   English   中英

使用2D数组创建可单击的TKinter画布

[英]Using 2d array to create clickable TKinter canvas

我想创建一个由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()

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

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

尝试遍历列表,并在每个条目中将Button-1事件绑定到canvas对象,因此:

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

那应该可以很好地设置您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM