You need to enable JavaScript to run this app. 如何在.kv文件中调用.py编写的Kivy下拉菜单并正常显示
优惠活动
大模型
产品
解决方案
定价
更多

如何在.kv文件中调用.py编写的Kivy下拉菜单并正常显示

问题解决方法

你遇到的问题核心是没有触发下拉菜单的弹出逻辑,调整如下:

问题原因

  • 仅在show_object方法中返回下拉菜单实例没有实际作用,Kivy的DropDown组件必须调用open()方法才会弹出
  • 全局定义drop实例的写法不规范,建议放到对应Screen类内部维护,避免变量冲突
  • kv文件中按钮的点击事件只执行了返回操作,没有触发菜单弹出的核心逻辑

调整后代码

.py文件修改
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.app import App

# 保留你原有exercises列表的定义即可
exercises = [
    ["占位"],
    ["俯卧撑"],
    ["深蹲"],
    ["引体向上"]
]

class AddExerciseScreen(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 下拉菜单放到类内部初始化,不要用全局变量
        self.drop = DropDown()
        for i in range(1, len(exercises)):
            btn = Button(text=exercises[i][0], size_hint_y=None, height=50)
            # 可选:添加菜单选项点击逻辑,点击后更新按钮文本并关闭菜单
            btn.bind(on_release=lambda btn: self.on_menu_select(btn.text))
            self.drop.add_widget(btn)

    def show_object(self, trigger_btn):
        # 调用open方法,传入触发按钮作为锚点,菜单会自动显示在按钮下方
        self.drop.open(trigger_btn)
    
    def on_menu_select(self, item_text):
        # 这里可以自定义选中菜单项后的业务逻辑
        self.ids.menu_btn.text = item_text
        self.drop.dismiss()

# 保留你原有其他Screen类的定义
class HomeScreen(Screen):
    pass
class TimerScreen(Screen):
    pass

class LightweightApp(App):
    def build(self):
        sm = ScreenManager()
        sm.add_widget(HomeScreen(name='home'))
        sm.add_widget(TimerScreen(name='timerscreen'))
        sm.add_widget(AddExerciseScreen(name='addexercise'))
        return sm

if __name__ == '__main__':
    LightweightApp().run()
.kv文件修改
<AddExerciseScreen>:
    Button:
        id: menu_btn
        text: "Menu"
        size_hint: None, None
        size: root.width* 0.2, root.height*0.05
        pos: root.width*0.5, root.height*0.95
        # 点击时把当前按钮作为参数传入,用来定位菜单的弹出位置
        on_release: root.show_object(self)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 01:15:03