如何在Kivy中实现图片移动?小鸟点击上升后无法自动下落问题求助
问题原因&修复方案
- 缩进错误:
on_touch_down、on_touch_up方法当前和Bird类平级,不属于类成员方法,会导致逻辑归属异常。 - 定时器逻辑位置错误:
move_bird方法内部写了Clock.schedule_interval注册逻辑,会导致定时器重复注册越来越卡,且没有在游戏初始化时主动启动定时器,小鸟的移动逻辑根本不会被定时执行。 - 缺少属性定义:
GameScreen类中没有声明GRAVITY常量,运行时会抛出属性不存在的报错。
修复后Python代码
from kivy.uix.screenmanager import Screen from kivy.uix.image import Image from kivy.properties import NumericProperty from kivy.clock import Clock class GameScreen(Screen): # 重力常量,数值可根据实际效果调整 GRAVITY = 300 def __init__(self, **kwargs): super().__init__(**kwargs) # 游戏初始化时启动定时移动逻辑 Clock.schedule_interval(self.move_bird, 1/60) def move_bird(self, time_passed): bird = self.ids.bird bird.y = bird.y + bird.velocity * time_passed bird.velocity = bird.velocity - self.GRAVITY * time_passed class Bird(Image): velocity = NumericProperty(0) def on_touch_down(self, touch): self.source = "icons/bird2.png" self.velocity = 150 super().on_touch_down(touch) def on_touch_up(self, touch): self.source = "icons/bird1.png" super().on_touch_up(touch)
原有Kv布局代码无需修改,确保Bird类在kv加载前完成导入即可正常生效
FloatLayout: Bird: source: "icons/bird1.png" size_hint: None, None size: 475, 475 pos_hint: { "center_x": .5, "center_y": .4} id: bird
内容的提问来源于stack exchange,提问作者Tan
相关产品推荐
相关产品推荐

