如何 return canvas 的(行,列)位置的边界框作为网格元组

How to return the bounding box for the (row, column) position of a canvas as a tuple of grid

我正在尝试编写最终如下所示的代码:

画布只是一堆像素,所以我想做的只是添加一点额外的功能 使在那片海中航行更容易。稍后我将绘制矩形(好吧,正方形)到 canvas 表示实体。

为此,我需要左上角和右下角的像素坐标。 所以 get_bbox 允许从 Position(x,y) class 的实例进行翻译(这是我们喜欢的工作 因为它存储在我们的网格字典中)到这些像素坐标,使我们能够像处理网格一样轻松地处理 canvas。


class AbstractGrid(tk.Canvas):
    
    def __init__(self, master, rows, cols, width, height, **kwargs):
        """

        master: The window in which the grid should be drawn. 
        rows: The integer number of rows in the grid.
        cols: The integer number of columns in the grid.
        width: The width of the grid canvas (in pixels). 
        height: The height of the grid canvas (in pixels). 
        **kwargs: Any other additional named parameters appropriate to tk.Canvas.
        """
        master=self._master
        rows=self._rows
        cols=self._cols
        width=self._width
        height=self._height

        super().__init__(master, rows, cols, width, height, **kwargs)  
        
    def get_bbox(self, position):
        """
        Returns the bounding box for the (row, column) position;
        this is a tuple containing information about the pixel positions of the edges of the shape,
        in the form (x min, y min, x max, y max).

        """

我不知道怎么写get_bboxfunction.Would请大神指点一下好吗?

谢谢

这是简单的数学运算:

class AbstractGrid(tk.Canvas):

    def __init__(self, master, rows, cols, width, height, **kwargs):
        """

        master: The window in which the grid should be drawn.
        rows: The integer number of rows in the grid.
        cols: The integer number of columns in the grid.
        width: The width of the grid canvas (in pixels).
        height: The height of the grid canvas (in pixels).
        **kwargs: Any other additional named parameters appropriate to tk.Canvas.
        """
        super().__init__(master, width=width, height=height, **kwargs)

        self._rows = rows
        self._cols = cols
        self._width = width
        self._height = height
        # calculate the grid width and height
        self._grid_w = width / cols
        self._grid_h = height / rows

    def get_bbox(self, position):
        """
        Returns the bounding box for the (row, column) position;
        this is a tuple containing information about the pixel positions of the edges of the shape,
        in the form (x min, y min, x max, y max).

        """
        row, col = position
        x, y = col*self._grid_w, row*self._grid_h
        return x, y, x+self._grid_w, y+self._grid_h

请注意,我在 __init__():

中修复了以下行中的问题
        master=self._master # self.master is created implicitly
        rows=self._rows     # should swap LHS and RHS on these four lines
        cols=self._cols
        width=self._width
        height=self._height

另请注意,如果您想要 正方形 网格,最好指定单个网格大小而不是 rowscols.