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

Python3 Kivy框架下添加多个DropDown下拉菜单后全部失效如何解决

问题根因

核心原因是Python垃圾回收机制导致的:你在build()方法中创建的两个DropDown实例fdd、ndd都是方法内的局部变量,方法执行完成后会被自动回收销毁,因此点击按钮没有对应响应。
另外你的kv代码中没有给自定义下拉菜单设置固定宽度,会导致菜单弹出后显示异常,且点击选项后不会自动关闭下拉框。


修复方案

1. 修改主代码

将两个下拉菜单实例绑定为App的实例属性,避免被GC回收,同时给每个下拉选项的回调方法增加关闭下拉框的逻辑:

from kivy.app import App
from kivy.uix.stacklayout import StackLayout
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button

class FileDropDown(DropDown):
    def new(self):
        print('New')
        self.dismiss() # 点击后关闭下拉菜单

    def open_file(self):
        print('Open')
        self.dismiss()

    def save(self):
        print('Save')
        self.dismiss()

    def save_as(self):
        print('Save As')
        self.dismiss()

class NotesDropDown(DropDown):
    def judges(self):
        print('Judges')
        self.dismiss()

    def clubs(self):
        print('Clubs')
        self.dismiss()

    def locations(self):
        print('Locations')
        self.dismiss()

class AgilityApp(App):
    def build(self):
        root_widget = StackLayout(orientation='lr-tb')

        # 把下拉实例绑定为App的属性,避免被回收
        self.fdd = FileDropDown()
        fbutton = Button(text='File', size_hint=(None, None),
            size=(60,35))
        fbutton.bind(on_release=self.fdd.open)
        root_widget.add_widget(fbutton)

        self.ndd = NotesDropDown()
        nbutton = Button(text='Notes', size_hint=(None, None),
            size=(80,35))
        nbutton.bind(on_release=self.ndd.open)
        root_widget.add_widget(nbutton)

        return root_widget

AgilityApp().run()

2. 修改kv代码

给两个自定义下拉菜单设置固定宽度,避免显示异常:

<FileDropDown>:
    size_hint_x: None
    width: 120 # 可按需调整宽度
    Button:
        id: new
        text: 'New'
        size_hint_y: None
        height: 35
        on_release: root.new()
    Button:
        id: open
        text: 'Open'
        size_hint_y: None
        height: 35
        on_release: root.open_file()
    Button:
        id: save
        text: 'Save'
        size_hint_y: None
        height: 35
        on_release: root.save()
    Button:
        id: save_as
        text: 'Save As'
        size_hint_y: None
        height: 35
        on_release: root.save_as()

<NotesDropDown>:
    size_hint_x: None
    width: 120 # 可按需调整宽度
    Button:
        id: judges
        text: 'Judges'
        size_hint_y: None
        height: 35
        on_release: root.judges()
    Button:
        id: clubs
        text: 'Clubs'
        size_hint_y: None
        height: 35
        on_release: root.clubs()
    Button:
        id: locations
        text: 'Locations'
        size_hint_y: None
        height: 35
        on_release: root.locations()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:24:03