Search code examples
pythonkivy

AttributeError: 'MyApp' object has no attribute 'ids'. Why this happens?


I'm a beginner, picking up the code piece by piece. I just don't have time to learn Kivy library, so I try my best to write functionality of my program. The man gave me my correct code, but I honestly don't understand why it gives me an error and how to fix it. Help me please <3

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import Button

KV = """
BoxLayout:
    id: bl
    orientation: "vertical"
    padding: [5] 
    spacing: 10
"""

class MyButton(Button):
    color=(0, 0, 0, 1)
    valign='bottom'
    padding_y=10
    background_color=(.93, .91, .67, 1)
    background_normal=''
 
class MyApp(App):
  
    def build(self):

        return Builder.load_string(KV)

    def on_start(self)
        
        self.ids.bl.add_widget(MyButton(text='И. С. Тургенев. «Отцы и дети»', on_press=self.btn_press))

    def btn_press(self,instance):
        self.ids.bl.clear_widgets()
        sc = ScrollView(size_hint=(1, None))
        x = 1
        data = ''
        while True:
            if x == 1:
                url = "http://loveread.ec/read_book.php?id=12021&p=1"
            elif x < 57:
                url = "http://loveread.ec/read_book.php?id=12021&p=" + f'{x}'
            else:
                break
            request = requests.get(url)
            soup = BeautifulSoup(request.text, "html.parser")
            teme = soup.find_all("p", class_="MsoNormal")
            for temes in teme:
                data += temes.text
            x = x + 1
        sc.add_widget(Label(text=f'{data}'))
        self.ids.bl.add_widget(sc)

Solution

  • Oops. Sorry, my mistake. The problem is that you cannot assign an id to the root widget in a kv rule. So the correct fix for your code is to replace:

    self.ids.bl.add_widget
    

    with just:

    self.root.add_widget