You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy Python导航代码不生效,按钮点击callback未触发如何修复?

Kivy页面导航切换问题修复方案

核心问题

  • 桌面平台分支下的B1按钮未绑定on_press回调事件,只有移动端分支做了绑定,导致桌面端点击按钮无响应
  • 导航体系未正确搭建:ScreenManager类ThirdWindow从未被实例化使用,App根视图直接返回了非Screen类型的Dre实例,导致manager属性不存在
  • update_bg方法绑定了尺寸/位置变化事件,每次触发都会重复添加标签和按钮,造成控件冗余

修复后完整代码

import kivy
from kivy.app import App
from kivy.core.audio import SoundLoader
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.graphics import Rectangle
from kivy import platform
from kivy.uix.screenmanager import ScreenManager, Screen

class MainWindow(Screen):
    pass

class Dre(Screen):
    def __init__(self, **kwargs):
        super(Dre, self).__init__(**kwargs)
        self.color = [254/255, 102/255, 37/255, 1]
        self.H_color = [254/255, 102/255, 37/255]
        self.sound_theme = None
        self.init_audio()

        # 适配不同平台的资源和样式
        if platform in ('linux', 'win', 'macosx'):
            bg_source = 'Neo.png'
            font_size = '60dp'
        else:
            bg_source = 'Neon.png'
            font_size = '30dp'
            
        with self.canvas.before:
            self.bg = Rectangle(size=self.size, source=bg_source)

        self.bind(pos=self.update_bg)
        self.bind(size=self.update_bg)
        
        # 控件仅初始化时添加一次
        self.add_widget(Label(text='D  R  E  A  M  S',
                      pos_hint={'center_x': .5, 'center_y': .8},
                      font_size=font_size, font_name='Roboto-Bold.ttf', color=self.H_color))
        B1 = Button(text='P L A Y', font_name='Roboto-Bold.ttf', size_hint=(.2, .15),
                 pos_hint={'center_x': .5, "center_y": .3}, background_color = self.color, background_normal='',
                 on_press=self.callback)
        self.add_widget(B1)

    def update_bg(self, *args):
        # 仅更新背景参数,不重复生成控件
        self.bg.pos = self.pos
        self.bg.size = self.size

    def callback(self, instance):
        print('working')
        self.manager.current = 'SecondWindow'

    def init_audio(self):
        self.sound_theme = SoundLoader.load('Bg_theme.mp3')
        if self.sound_theme:
            self.sound_theme.volume = 1
            self.sound_theme.loop = True
            self.sound_theme.play()
            print('okay')
        else:
            print('not okay')


class SecondWindow(Screen):
    def __init__(self, **kwargs):
        super(SecondWindow, self).__init__(**kwargs)
        self.color = [254 / 255, 102 / 255, 37 / 255, 1]
        with self.canvas.before:
            self.bg = Rectangle(size=self.size, color=self.color)
        self.bind(pos=self.update_bg, size=self.update_bg)
        
    def update_bg(self, *args):
        self.bg.pos = self.pos
        self.bg.size = self.size


class LabApp(App):
    def build(self):
        # 初始化导航管理器,注册所有页面
        sm = ScreenManager()
        sm.add_widget(Dre(name='Dre'))
        sm.add_widget(SecondWindow(name='SecondWindow'))
        sm.current = 'Dre'
        return sm


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

关键修改说明

  • 将Dre类的继承关系从RelativeLayout改为Screen,使其可以获取manager属性实现页面切换
  • 统一了全平台的按钮回调绑定逻辑,所有场景下点击B1都会触发callback
  • 把标签、按钮的添加逻辑从update_bg移到__init__,避免窗口尺寸变化时重复生成控件
  • 删除了未使用的ThirdWindow类,在App的build方法中直接初始化ScreenManager作为根视图,完成导航体系搭建

内容的提问来源于stack exchange,提问作者Alt_2003

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 22:27:03