Kivy:如何使用 on_touch_move 函数更改小部件的大小?

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

作为初学者 python 学习者,我正在尝试使用 kivy 创建这个简单的应用程序,通过各种输入来改变矩形的粗细。首先,我曾尝试使用按钮来完成它,并在这个社区的帮助下设法让它工作。

既然这个问题已经解决了,我想更上一层楼,使用on_touch_move功能在屏幕上滑动改变粗细。但是又遇到了新问题

当我 运行 这段代码时,没有错误,boundary_thickness_xboundary_thickness_y 也在更新(使用打印测试)。但是小部件的大小(厚度)没有在 window.

中更新

我想知道我可能犯了什么错误?

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

您的 on_touch_move() 方法没有调整正确的属性。它只是调整几个局部变量。只需将该方法更改为:

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

您必须使用 self. 来引用属性。