Kivy:如何使用按钮更改小部件的大小?

Kivy: How to change size of widget by using a button?

刚开始学习python,对OOP半信半疑。所以只是尝试通过使用 kivy 构建一个非常简单的应用程序来练习。这个想法是让球在屏幕内弹跳。在这样做的同时,可以通过按下按钮来增加边界的厚度,因此球弹跳的区域会更小。

但是在编程边界行为的第一步中遇到了问题。 我在 .kv 文件中创建了边界,并使用变量 boundary_thickness 给它一个初始值 10。并使用 boundaryIncrease 方法在按下按钮时更新此值。

在 运行 代码之后,我没有收到任何错误,但按下按钮也不会改变边界厚度。但我确实观察到,如果我调整 window 的大小,按下按钮后,boundary_thickness 确实会更新为新值,并且边界的厚度会增加。

有没有办法实时更新这个值,而不必每次都调整 window 的大小?

或者纠正我所犯错误的方法?

P.S。对编程世界来说是全新的。

提前致谢:)

**main.py**

from kivy.app import App
from kivy.uix.widget import Widget

class BounceGame(Widget):
    boundary_thickness = 10
    
    def boundaryIncrease(self):
        self.boundary_thickness += 5

class BounceApp(App):
    def build(self):
        return BounceGame()

BounceApp().run()
**bounce.kv**

<BounceGame>
    canvas: 
        Rectangle:
            pos : 0, 0
            size: self.boundary_thickness, root.height

        Rectangle:
            pos : 0, 0
            size: root.width, self.boundary_thickness

        Rectangle:
            pos : root.width - self.boundary_thickness, 0
            size: self.boundary_thickness, root.height

        Rectangle:
            pos : 0, root.height - self.boundary_thickness
            size: root.width, self.boundary_thickness

    Button:
        center: root.center_x, root.center_y
        text: "Button"
        on_press: root.boundaryIncrease()

您需要使用 NumericProperty 让 kivy 在 screen.So 上更新此值 让我们导入此 属性:

from kivy.properties import NumericProperty

现在将您的 boundary_thickness 更改为:

boundary_thickness = NumericProperty(10)

就是这样。