Kivy: AttributeError: у объекта 'CreateButton' нет атрибута '_disabled_count' - PullRequest
0 голосов
/ 18 апреля 2020

Я пытаюсь создать панель кнопок на сенсорном экране Raspberry Pi в качестве домашнего хобби, и я хочу создать несколько кнопок, которые вы нажимаете и отпускаете, некоторые из которых включаются и выключаются, а другие имеют несколько состояний.

Я хочу изменить состояние кнопки при ее нажатии. Таким образом, я могу определить, что кнопка нажата с помощью класса CreateButton, но я хочу передать информацию о состоянии кнопки в init . Когда я это делаю, я получаю

AttributeError: у объекта 'CreateButton' нет атрибута '_disabled_count'

Если я удаляю init в CreateButton код работает, чего я не понимаю. Можете ли вы предложить, где я иду не так?

Большое спасибо

Main.py

import pickle
from kivy.app import App
from kivy.uix.image import AsyncImage
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from typing import List

# Define the data structure of a button state
class StateDefinition(object):
    def __init__(self, Label, Image, Colour, Action):
        self.Label = Label
        self.Image = Image
        self.Colour = Colour
        self.Action = Action

# Define the data structure of a button
class ButtonDefinition(object):
    def __init__(self, buttonname: str, currentstate: int, buttonstates: List[StateDefinition]):
        self.currentstate = currentstate
        self.buttonname = buttonname
        self.buttonstates = buttonstates

# Define the data structure of a dashboard - a collection of related buttons
class DashboardDefinition(object):
    def __init__(self, dashboardname: str, dashboardbuttons: List[ButtonDefinition]):
        self.dashboardname = dashboardname
        self.dashboardbuttons = dashboardbuttons

# This class creates the kivy button and binds it to the action
class CreateButton(Button):
    def __init__(self, **kwargs):
        print("Got Here")

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            if touch.button == "right":
                print(self.id, "right mouse clicked")
            elif touch.button == "left":
                print(self.id, "left mouse clicked")
            else:
                print(self.id)
            return True
        return super(CreateButton, self).on_touch_down(touch)

## This is the class that builds the Carousel of buttons
class BuildLayout(GridLayout):

    def __init__(self, **kwargs):
        super(BuildLayout, self).__init__(**kwargs)
        self.build_dashboard()

    def build_dashboard(self):

        # Define all the test data
        state1 = StateDefinition(Label = 'State 1', Image = 'Image1.png', Colour = '#FF0000', Action = 'A')
        state2 = StateDefinition(Label = 'State 2', Image = 'Image2.png', Colour = '#00FF00', Action = 'B')
        state3 = StateDefinition(Label = 'State 3', Image = 'Image3.png', Colour = '#0000FF', Action = 'C')
        button1 = ButtonDefinition(buttonname = "Button 1", currentstate = 0, buttonstates = [state1])
        button2 = ButtonDefinition(buttonname = 'Button 2', currentstate = 0, buttonstates = [state2, state1])
        button3 = ButtonDefinition(buttonname = 'Button 3', currentstate = 0, buttonstates = [state3, state2, state1])
        dashboard1 = DashboardDefinition(dashboardname = "Test Dashboard", dashboardbuttons = [button1, button2, button3])

        for buttonID in range(0, len(dashboard1.dashboardbuttons)):
            buttonwidget = CreateButton(id = str(buttonID))
            buttonwidget.text = dashboard1.dashboardbuttons[buttonID].buttonname + "\nButton State: " + \
                                str(dashboard1.dashboardbuttons[buttonID].currentstate)
            self.add_widget(buttonwidget)

# This is tha main class that sets up the app
class LayoutApp(App):
    def build(self):
        return BuildLayout()

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

Layout.kv

#:kivy 1.11.0

<CreateButton>:
    font_size: 18
    on_touch_down: self.on_touch_down

<BuildLayout>:
    rows: 3
    cols: 3
    row_force_default: True
    row_default_height: 150
    col_force_default: True
    col_default_width: 150
    padding: [10]
    spacing: [10]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...