Search code examples
pythonkivy

How do I pass a function with an argument to on_press?


I'm writing a simple mobile app that parses information from the site and displays it on the screen. But the problem is that when I click the button, all widgets should be removed and only the text that I parsed from the site should remain. To do this I should pass to the function on_press the argument of my BoxLayout, but it just doesn't work. Code:

class MyApp(App):

    def build(self):
        bl = MyBoxLayout(orientation='vertical', padding=[5], spacing=10)
        bl.add_widget(MyButton(text='И. С. Тургенев. «Отцы и дети»', on_press = self.btn_press(bl)))

    

def btn_press(self,bl):
    bl.clear_widgets()
    sc = MyScrollView(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 < 5:
            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
            print(temes.text)
        x = x + 1
    bl.add_widget(Label(text=data, color=(0, 0, 0, 1),font_size = 17,halign='left',
                        valign='top'))
    sc.add_widget(bl)
    return sc



Also I have a lot of errors with outputting ScrollView. (Please help me as a newbie)


Solution

  • Typically when you're passing a function as an argument, the intent is that you want the function to be called later, in response to some event.

    In such cases, you want to pass only the function name, without the parentheses, like so:

    on_press = self.btn_press
    

    If you include the parentheses, as you did in your example, the function is called immediately which isn't what you want.