python - 在网格旁边添加按钮
问题描述
我正在尝试看起来像这样的东西
这是一个类似于绘画的程序。我已经对网格进行了编程,当我单击一个单元格时,它将被涂成黑色,但是我不知道如何在网格旁边添加按钮。我尝试了不同的方法,但总是收到错误消息。这是我第一次使用 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()
解决方案
首先创建两个框架。一帧用于网格,另一帧用于按钮。用于pack
将两个框架并排放置。
然后,您可以创建按钮并使用pack
将它们从上到下放置在右侧,并grid
在左侧创建正方形网格。
推荐阅读
- arrays - Laravel syntax error in trying to load simple view: unexpected '=>' (T_DOUBLE_ARROW), expecting ']'
- javascript - 将类的静态方法转换为变量打字稿
- gstreamer - 缺少 gstreamer 插件
- python - 什么是'NameError: name 'R' is not defined'错误,我们如何纠正它?
- javascript - 尝试使用 map.filter 写出一系列元素来过滤我的结果时出错
- java - Having an OutputStream write in a C buffer using JNI
- python - Python:如何从 3D 坐标集合创建曲面图
- python - 在扭曲的图像上查找角点
- python-3.8 - 使用 pip3 安装 Networkit 的问题
- r - 更改图形图例以指示线型...(ggplot2)