【发布时间】:2021-02-14 19:37:37
【问题描述】:
我正在尝试一些看起来像这样的东西
这是一个类似于绘画的程序。我已经对网格进行了编程,当我单击一个单元格时,它将被涂成黑色,但是我不知道如何在网格旁边添加按钮。我尝试了不同的方法,但总是收到错误消息。这是我第一次使用 python 编程并使用画布,如果有人能帮我解决这个问题,我将不胜感激。
This is the code I have
from tkinter import *
class Grilla:
colorCelda = "black"
colorDefault = "white"
colorBorde = "black"
bordeDefault = "black"
def __init__(self, root, master, x, y, size):
""" Constructor of the object called by Cell(...) """
self.master = master
self.abs = x
self.ord = y
self.size = size
self.fill = False
def switch(self):
""" Switch if the cell is filled or not. """
self.fill = not self.fill
def draw(self):
# dibujar en el canvas
if self.master is not None:
outline = Grilla.colorBorde
fill = Grilla.colorCelda
if not self.fill:
outline = Grilla.bordeDefault
fill = Grilla.colorDefault
xmin = self.abs * self.size
xmax = xmin + self.size
ymin = self.ord * self.size
ymax = ymin + self.size
self.master.create_rectangle(xmin, ymin, xmax, ymax, fill=fill, outline=outline)
class CellGrilla(Canvas):
def __init__(self, master, numFil, numCol, tamGrid, *args, **kwargs):
Canvas.__init__(self, master, width=tamGrid * numCol, height=tamGrid * numFil, *args, **kwargs)
self.cellSize = tamGrid
self.grid = []
for row in range(numFil):
line = []
for column in range(numCol):
line.append(Grilla(self, column, row, tamGrid))
self.grid.append(line)
# memorize the cells that have been modified to avoid many switching of state during mouse motion.
self.switched = []
# bind click action
self.bind("<Button-1>", self.handleMouseClick)
self.draw()
def draw(self):
for row in self.grid:
for cell in row:
cell.draw()
def _coordenadas(self, event):
row = int(event.y / self.cellSize)
column = int(event.x / self.cellSize)
return row, column
def handleMouseClick(self, event):
row, column = self._coordenadas(event)
cell = self.grid[row][column]
cell.switch()
cell.draw()
if __name__ == "__main__":
app = Tk()
# Tamaño de canvas x tamaño de pixeles
grid = CellGrilla(app, 50, 50, 10)
grid.pack()
app.mainloop()
【问题讨论】:
标签: python tkinter tkinter-canvas