简体   繁体   中英

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

I have just started learning python and am semi-confident in OOP. So just trying to practice by building a very simple app using kivy. The idea is to make a ball bounce inside a screen. While doing so, the thickness of the boundaries can be increased by pressing a button, so the ball would have less area to bounce.

But have an issue in the very first step of programming the boundary behavior. I have created the boundaries in .kv file and used a variable boundary_thickness to give it an initial value of 10 . And using a boundaryIncrease method to update this value whenever the button is pressed.

After running the code, I'm not getting any error, but pressing the button also does not change the boundary thickness. But I did observe, that after pressing the button if I resize the window, the boundary_thickness does get updated to the new value, and the boundary's thickness increases.

Is there a way to update this value in real-time, without having to resize the window every time?

Or a way to correct whatever mistake that I have made?

PS Completely new to the programming world.

Thanks in advance:)

**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()

You need to use NumericProperty for let kivy to update this value on screen.So lets import this property:

from kivy.properties import NumericProperty

Now change your boundary_thickness to that:

boundary_thickness = NumericProperty(10)

Thats it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM