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

时间:2020-08-05 07:07:30

标签: python widget kivy size touch-event

作为初学者python学习者,我正在尝试使用kivy创建这个简单的应用,以通过各种输入来更改矩形的厚度。首先,我尝试使用按钮进行操作,并在该社区的一些帮助下设法使其正常工作。

现在此问题已解决,我想通过使用on_touch_move函数在屏幕上滑动以更改厚度来将其提升到一个新的水平。但是又偶然发现了一个新问题。

运行此代码时,没有错误,boundary_thickness_xboundary_thickness_y也正在更新(使用打印进行测试)。但是窗口小部件的大小(厚度)不会在窗口中更新。

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

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

1 个答案:

答案 0 :(得分:0)

您的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.来引用属性。