简体   繁体   中英

Kivy: How to change size of widget using on_touch_move function?

As a beginner python learner, I am trying to create this simple app using kivy to change the thickness of a rectangle through various inputs. Firstly, I had tried to do it using buttons, and with some help from this community managed to make it work.

Now that this problem got solved, I thought of taking it to the next level by using the on_touch_move function to slide on the screen to change thickness. But have again stumbled across a new problem.

When I run this code, there is no error, also the boundary_thickness_x and boundary_thickness_y are getting updated (tested using print). But the size (thickness) of the widgets is not updating in the window.

I wonder what mistake I might be doing?

**main.py**

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ObjectProperty

class Boundary(Widget):

    boundary_thickness_x = NumericProperty(10)
    boundary_thickness_y = NumericProperty(10)

    def on_touch_move(self, touch):
        x = touch.x/self.width * 100
        y = touch.y/self.height * 100

        boundary_thickness_x = x
        boundary_thickness_y = y
        
        #print(boundary_thickness_x, boundary_thickness_y)
    
class BounceApp(App):
    def build(self):
        return Boundary()

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

<Boundary>
    canvas: 
        Rectangle:
            pos : 0, 0
            size: self.boundary_thickness_x, root.height

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

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

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

Your on_touch_move() method is not adjusting the correct properties. It is only adjusting a couple local variables. Just change that method to:

def on_touch_move(self, touch):
    x = touch.x / self.width * 100
    y = touch.y / self.height * 100

    self.boundary_thickness_x = x
    self.boundary_thickness_y = y

You must use self. to reference the properties.

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