【问题标题】:How can I just make my widget move in Kivy?我怎样才能让我的小部件在 Kivy 中移动?
【发布时间】:2019-10-03 10:15:43
【问题描述】:

我没有太多的编程经验,只是从 Kivy 开始。我无法在 Kivy 文档和 youtube 中找到组合所有内容的方式,在这种情况下,让我的小部件移动。特别是结合了 kv 和 python 以及不同的布局。

现在,如果我按下左键,我设法打印出“工作中”。 相反,我想让我的小部件(汽车图像)自动向前移动并使用 2 个按钮左右旋转汽车应该转弯。

期待看到一些建议。我也希望有很多 Kivy 经验的人有一些关于如何处理 kivy 文档和一般 kivy 的提示。

这是我的 Python 代码:

import kivy
kivy.require('1.11.1')
from kivy.app import App
from kivy.uix.label import Label # add some text
from kivy.uix.stacklayout import StackLayout
from kivy.uix.gridlayout import GridLayout #
from kivy.uix.textinput import TextInput #for textinput ;)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.pagelayout import PageLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.image import Image, AsyncImage
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.button import Button
from kivy.uix.behaviors import ButtonBehavior
from kivy.graphics import Rectangle, Color
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.scatterlayout import ScatterLayout
from kivy.config import Config
from kivy.core.window import Window
from kivy.properties import ObjectProperty, NumericProperty, ReferenceListProperty, ListProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.lang import Builder
import os

Window.size = (450, 750)

print(dir(Widget))

class myGame(FloatLayout):

    def leftButton(self, *args):
        btnLeft = self.ids['btnLeft']
        Car.moveCar(self)

    def rightButton(self, *args):
        btnRight = self.ids['btnLeft']
        print('right button')


class Car(Widget):
    def moveCar(self):
        car = self.ids['car']
        print('working')




class myApp(App): #name your .kv file 'my.kv'
    def build(self): # initialization method, like __init__
        game = myGame()
        return game

if __name__ == '__main__':
    myApp().run()

这是我的 kv 代码:

#:kivy 1.11.1


#<Button>:
    #size_hint: 0.5, 0.27

<FloatLayout>:
    Button:
        id: btnLeft
        pos_hint: {'x': 0, 'bottom': 1}
        size_hint: 0.5, 0.27
        on_press: root.leftButton()
        Image:
            source: 'images/arrow_left.png'
            allow_stretch: True
            keep_ratio: False
            center_x: self.parent.center_x
            center_y: self.parent.center_y  
            size: root.width * 0.5, root.height * 0.27


    Button:
        id: btnRight
        pos_hint: {'x': 0.5, 'bottom': 1}
        size_hint: 0.5, 0.27
        on_press: root.rightButton()
        Image:
            source: 'images/arrow_right.png'
            allow_stretch: True
            keep_ratio: False
            center_x: self.parent.center_x
            center_y: self.parent.center_y  
            size: root.width * 0.5, root.height * 0.27


    Car:      # the Car
        id: car
        canvas:
            Rectangle:
                source: 'images/car_blue_5.png'
                size: root.width * 0.15, root.height * 0.15
                pos: root.width * 0.425, root.height * 0.44

【问题讨论】:

    标签: python-3.x layout widget kivy kivy-language


    【解决方案1】:

    进行Widget 移动的一种方法是使用Animation,但如果您想继续更改移动(转向),那么您可能需要自己制作动画。这是执行此操作的代码版本:

    import kivy
    kivy.require('1.11.1')
    from kivy.app import App
    from kivy.uix.floatlayout import FloatLayout
    from kivy.uix.widget import Widget
    from kivy.core.window import Window
    from kivy.properties import NumericProperty, ListProperty
    from kivy.clock import Clock
    from kivy.lang import Builder
    
    import math
    
    Window.size = (450, 750)
    
    class myGame(FloatLayout):
    
        def leftButton(self, *args):
            self.ids.car.direction_angle += 2
    
        def rightButton(self, *args):
            self.ids.car.direction_angle -= 2
    
    
    class Car(Widget):
        speed = NumericProperty(20)
        direction_angle = NumericProperty(0)   # degrees
        direction = ListProperty([0,1])
    
        def __init__(self, **kwargs):
            super(Car, self).__init__(**kwargs)
            Clock.schedule_interval(self.moveCar, 0.1)
    
        def moveCar(self, dt):
            radians = self.direction_angle * math.pi / 180.0
            self.direction = math.sin(-radians), math.cos(-radians)
            self.pos = (self.x + dt * self.speed * self.direction[0], self.y + dt * self.speed * self.direction[1])
    
    
    Builder.load_string('''
    #:kivy 1.11.1
    
    
    #<Button>:
        #size_hint: 0.5, 0.27
    
    <FloatLayout>:
        Button:
            id: btnLeft
            pos_hint: {'x': 0, 'bottom': 1}
            size_hint: 0.5, 0.27
            on_press: root.leftButton()
            Image:
                source: 'images/arrow_left.png'
                allow_stretch: True
                keep_ratio: False
                center_x: self.parent.center_x
                center_y: self.parent.center_y  
                size: root.width * 0.5, root.height * 0.27
    
    
        Button:
            id: btnRight
            pos_hint: {'x': 0.5, 'bottom': 1}
            size_hint: 0.5, 0.27
            on_press: root.rightButton()
            Image:
                source: 'images/arrow_right.png'
                allow_stretch: True
                keep_ratio: False
                center_x: self.parent.center_x
                center_y: self.parent.center_y  
                size: root.width * 0.5, root.height * 0.27
    
    
        Car:      # the Car
            id: car
            size_hint: None, None
            size: root.width * 0.15, root.height * 0.15
            pos: root.width * 0.425, root.height * 0.44
            canvas.before:
                PushMatrix
                Rotate:
                    angle: self.direction_angle
                    origin: self.center
            canvas:
                Rectangle:
                    source: 'images/car_blue_5.png'
                    size: self.size
                    pos: self.pos
            canvas.after:
                PopMatrix
    ''')
    
    
    class myApp(App): #name your .kv file 'my.kv'
        def build(self): # initialization method, like __init__
            game = myGame()
            return game
    
    if __name__ == '__main__':
        myApp().run()
    

    Car__init__() 方法使用Clock.schedule_interval() 调用启动动画,每秒更新Car 位置10 次。

    Car 的移动在moveCar() 方法中计算,并使用direction_anglespeed 来更新位置。

    Buttons调整direction_angle属性,用于Carcanvas改变其方向。

    【讨论】:

    • 非常感谢约翰!很高兴看到它工作。很好的参考代码和正确的值来理解代码中发生的事情:) 我想我可以从这里走得更远!
    【解决方案2】:

    在许多戏剧中,您必须使用动画,它使您的小部件持续移动并朝特定方向移动,并且很容易从时钟开始。

    当你想移动汽车时,我使用这个应用程序,你必须多次按下按钮,但在动画中,你可以在你按下按钮时开始动画,当你释放按钮时停止动画如果你愿意,动画会重复,请访问.

    https://kivy.org/doc/stable/api-kivy.animation.html

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2013-04-15
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多