首页 > 解决方案 > 在网格旁边添加按钮

问题描述

我正在尝试看起来像这样的东西

在此处输入图像描述

这是一个类似于绘画的程序。我已经对网格进行了编程,当我单击一个单元格时,它将被涂成黑色,但是我不知道如何在网格旁边添加按钮。我尝试了不同的方法,但总是收到错误消息。这是我第一次使用 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()

标签: pythontkintertkinter-canvas

解决方案


首先创建两个框架。一帧用于网格,另一帧用于按钮。用于pack将两个框架并排放置。

然后,您可以创建按钮并使用pack将它们从上到下放置在右侧,并grid在左侧创建正方形网格。


推荐阅读