Kivy小部件画布中的相对尺寸的矩形

时间:2020-07-17 09:18:09

标签: python kivy

我创建了以下Widget,它可以正确绘制棋盘格图案。但是,edge_len变量(显然)没有遵循所声明的定义。

        with self.canvas:
        # Define the lengths of the edges of the squares. TODO: Check for relative growth.
        edge_len = min(self.height, self.width) // 8
        for column in range(0, 8):
            for row in range(0, 8):
                if ((row + column) % 2) == 0:
                    graphics.Color(0, 0, 1)
                    self.dark_rect = graphics.Rectangle(pos=(column*edge_len, row*edge_len), size=(edge_len, edge_len))
                else:
                    graphics.Color(1, 1, 1)
                    self.light_rect = graphics.Rectangle(pos=(column*edge_len, row*edge_len), size=(edge_len, edge_len))

我当前正在运行该应用程序以返回一个Boxlayout()并将此小部件作为其唯一元素。当edge_len = min(self.height, self.width) // 8在那里时,它使电路板很小。相反,当使用edge_len = min(self.height, self.width)时,第八个棋盘格拼贴的确终止于窗口的宽度,但延伸得比该宽度高得多。

我正在尝试找出如何使绘制的结果相对于其布局容器/子项相对大小,但仍然完美地保持正方形。

1 个答案:

答案 0 :(得分:0)

Kivy提供了文档here

这是相关的代码更改:

    def __init__(self, **kwargs):
        super(Chessboard, self).__init__(**kwargs)
        self.bind(pos=self.drawBoardandPieces)
        self.bind(size=self.drawBoardandPieces)
        self.drawBoardandPieces()

    def drawBoardandPieces(self, *args):
        with self.canvas:
            # Reset everything in case of redraws.
            self.canvas.clear()
            # Define the lengths of the edges of the squares. TODO: Check for relative growth.
            edge_len = min(self.height, self.width) // 8
            Config.set("graphics", "resizable", True)
            for column in range(0, 8):
                for row in range(0, 8):
                    if ((row + column) % 2) == 0:
                        graphics.Color(0, 0, 1)
                        self.dark_rect = graphics.Rectangle(pos=(column*edge_len, row*edge_len), size=(edge_len, edge_len))
                    else:
                        graphics.Color(1, 1, 1)
                        self.light_rect = graphics.Rectangle(pos=(column*edge_len, row*edge_len), size=(edge_len, edge_len))