簡體   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