python - 如何让 kivy 应用打开下拉菜单
问题描述
我正在尝试让一个 kivy 应用程序打开一个下拉列表。我在这里按照示例进行操作。
当我运行应用程序时,我可以单击按钮,但没有出现下拉菜单。
我错过了一些简单的东西,但我就是看不到它。有人可以帮忙吗。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.lang import Builder
root = Builder.load_string('''
<MainFrame>:
BoxLayout:
orientation: 'vertical'
Label:
text: 'Hello'
Button:
text: 'open dropdown'
on_press: root.on_menu_button_click()
''')
class MainFrame(Screen):
def __init__(self, **kwargs):
super(MainFrame, self).__init__(**kwargs)
self.dropdown = self._create_dropdown()
def _create_dropdown(self):
dropdown = DropDown()
for index in range(5):
btn = Button(text='Value %d' % index, size_hint_y=None, height=44)
btn.bind(on_release=lambda btn: dropdown.select(btn.text))
dropdown.add_widget(btn)
return dropdown
def on_menu_button_click(self):
self.dropdown.open
class BasicApp(App):
def build(self):
return MainFrame()
if __name__ == '__main__':
BasicApp().run()
解决方案
您必须使用该open()
方法并传递按钮,您还必须使用on_release
代替on_press
.
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.lang import Builder
root = Builder.load_string('''
<MainFrame>:
BoxLayout:
orientation: 'vertical'
Label:
text: 'Hello'
Button:
id: btn # <---
text: 'open dropdown'
on_release: root.on_menu_button_click(btn) # <---
''')
class MainFrame(Screen):
def __init__(self, **kwargs):
super(MainFrame, self).__init__(**kwargs)
self.dropdown = self._create_dropdown()
def _create_dropdown(self):
dropdown = DropDown()
for index in range(5):
btn = Button(text='Value %d' % index, size_hint_y=None, height=44)
btn.bind(on_release=lambda btn: dropdown.select(btn.text))
dropdown.add_widget(btn)
return dropdown
def on_menu_button_click(self, widget): # <---
self.dropdown.open(widget) # <---
class BasicApp(App):
def build(self):
return MainFrame()
if __name__ == '__main__':
BasicApp().run()
示例中清楚地提到了上述内容,因为它表明:
...
# show the dropdown menu when the main button is released
# note: all the bind() calls pass the instance of the caller (here, the
# mainbutton instance) as the first argument of the callback (here,
# dropdown.open.).
mainbutton.bind(on_release=dropdown.open)
...
推荐阅读
- sql-server - 选择数据而不锁定行
- javascript - 无法使用反应挂钩读取未定义的属性“地图”
- javascript - 更新帖子时如何添加“删除”按钮
- javascript - 加载页面后如何添加元标记?
- webpack - 为什么 ttf 字体不能与 Vue CLI 一起使用?
- javascript - 为什么物化 css 和 *ngFor 的轮播不能动态协同工作以获取图像
- android - 如何将存储库注入 ViewModel?
- python-3.x - 使用 matplotlib 和 opencv 在 Python 中存储和检索图像
- c - 仅在控制台的左侧和右侧设置文本
- python - 'range' 对象不支持项赋值 int 赋值给数组