首页 > 解决方案 > 使用自定义类作为视图类时出现 RecycleView 错误

问题描述

为了更好地优化,我决定在程序的一部分中使用RecycleView来保存一组DownloadItem实例。问题是该类有两个参数:路径和 url_type,我不知道如何将其传递给 recylceview 的数据。结果,我收到以下错误:

 TypeError: __init__() missing 1 required positional argument: 'path'

我的python文件:

from kivy.lang import Builder
from kivymd.uix.card import MDCard
from kivymd.app import MDApp


class DownloadItem(MDCard):

    def __init__(self, path: str, url_type: str = "file", **kwargs):
        self.path = path
        self.url_type = url_type
        self.paused = False
        self.fill_animation = None
        # I later on use these variables in this class
        super(DownloadItem, self).__init__(**kwargs)

    # the rest of the class ...

class BitDownloader(MDApp):

    def __init__(self, **kwargs):
        global app
        super(BitDownloader, self).__init__(**kwargs)
        self.kv = Builder.load_file("design.kv")
        self.path = "C:/Users/Family/Downloads/"
        app = self

    def build(self):
        self.theme_cls.theme_style = "Dark"
        return self.kv

    def add_item(self):
        # I know that you need to pass kwargs only when appending to the data but I have no other clue what to do
        self.kv.ids.downloads_list.data.append({"path": self.path + '/' if self.path[-1] != '/' else self.path,
                                            "url_type": "file"})


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

我的 KV 文件:

#:kivy 2.0.0
<TooltipMDLabel@MDLabel+MDTooltip>
<DownloadItem>:
    orientation: "vertical"
    padding: 10
    spacing: 10
    size_hint_y: None
    height: 100
    elevation: 20
    border_radius: 5
    radius: [5]
    MDBoxLayout:
        adaptive_height: True
        spacing: 5
        MDIcon:
            icon: root.url_type
            size_hint_x: None
            width: self.texture_size[0]
        TooltipMDLabel:
            text: root.path if len(root.path) <= 30 else root.path[:31] + " ..."
            tooltip_text: f"Path: {root.path}\nType: {root.url_type}"
            tooltip_bg_color: app.theme_cls.bg_darkest
            tooltip_text_color: app.theme_cls.opposite_bg_darkest
            size_hint_y: None
            height: self.texture_size[1]
    MDSeparator:
    MDBoxLayout:
        spacing: 10
        MDProgressBar:
            id: progress_bar
            min: 0
            max: 100
            value: 50
            color: app.theme_cls.primary_color
        MDIconButton:
            id: pause_resume_button
            icon: "pause"
            pos_hint: {"center_x": .5, "center_y": .5}
        MDIconButton:
            icon: "close"
            pos_hint: {"center_x": .5, "center_y": .5}
BoxLayout:
    orientation: "vertical"
    spacing: 10
    RecycleView:
        id: downloads_list
        viewclass: "DownloadItem"
        RecycleBoxLayout:
            default_size: None, dp(56)
            default_size_hint: 1, None
            size_hint_y: None
            height: self.minimum_height
            orientation: "vertical"
            padding: 15
            spacing: 15
    MDRaisedButton:
        text: "Add"
        size_hint_x: 1
        on_release: app.add_item()

标签: pythonpython-3.xkivykivymd

解决方案


为了DownloadItem在您的中使用kv,它必须有一个__init__()不带必需参数的。这是一个使用属性而不是必需参数的版本:

class DownloadItem(MDCard):
    path = StringProperty()
    url_type = StringProperty('file')

    def __init__(self, **kwargs):
        # self.path = path
        # self.url_type = url_type
        self.paused = False
        self.fill_animation = None
        # I later on use these variables in this class
        super(DownloadItem, self).__init__(**kwargs)

推荐阅读