KivyMD创建dropdown menu触发open()参数数量不符报错如何解决
KivyMD下拉菜单TypeError修复方案
错误原因
这个报错是因为KivyMD 1.0.0及以上版本对MDDropdownMenu的API做了不兼容调整:
- 旧版本
open()方法需要传入触发菜单的控件作为参数 - 新版本触发控件需要在初始化
MDDropdownMenu时通过caller参数指定,open()方法不需要接收任何额外参数 - 旧版的
MDMenuItem已被废弃,改用基础的列表项组件如OneLineListItem替代
具体修改点
1. 修改Python代码
调整MDDropdownMenu的初始化逻辑,提前构造菜单项列表,指定caller参数:
from kivy.properties import ObjectProperty from kivymd.uix.menu import MDDropdownMenu from kivymd.app import MDApp import win32api drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] class YouTubeDownloader(MDApp): dropdown = ObjectProperty() def on_start(self): # 构造菜单项列表 menu_items = [ { "viewclass": "OneLineListItem", "text": str(i), "height": 50, "on_release": lambda x=str(i): self.menu_callback(x) } for i in drives ] # 初始化下拉菜单时指定caller为触发按钮 self.dropdown = MDDropdownMenu( caller=self.root.ids.dropdown, items=menu_items, width_mult=4 ) def menu_callback(self, text_item): print(text_item) # 点击后关闭菜单 self.dropdown.dismiss() YouTubeDownloader().run()
2. 修改KV代码
把open(self)改成不需要参数的open():
BoxLayout: orientation:"vertical" MDToolbar: title:"YouTube Downloader" md_bg_color: app.theme_cls.primary_color BoxLayout: orientation:"vertical" MDTextField: hint_text: "Enter the URL here" size_hint: 0.4,0.15 pos_hint:{"center_x":0.5,"center_y":0.5} MDRaisedButton: id: dropdown text: "Select Path" pos_hint:{"center_x":0.5} on_release: app.dropdown.open() GridLayout: cols:3 AsyncImage: id: image source: "https://i.ytimg.com/vi/LRXo0juuTrw/maxresdefault.jpg" AsyncImage: source: "https://i.ytimg.com/vi/LRXo0juuTrw/maxresdefault.jpg" AsyncImage: source: "https://i.ytimg.com/vi/LRXo0juuTrw/maxresdefault.jpg" AsyncImage: source: "https://i.ytimg.com/vi/LRXo0juuTrw/maxresdefault.jpg" MDRaisedButton: text:"Download" pos_hint:{"center_x":0.5}
修改后即可正常触发下拉菜单,选择菜单项后会自动打印对应盘符并关闭菜单。
内容的提问来源于stack exchange,提问作者user16461495
相关产品推荐
相关产品推荐

