![](/img/trans.png)
[英]How to make a grid consisting of rectangles so that each rectangle can be used further in the code using its position (a tuple of row and column)?
[英]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_bbox function。你能幫我一個辦法嗎?
謝謝
這是簡單的數學:
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
另請注意,如果您想要方形網格,最好指定單個網格大小而不是rows
, cols
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.