Saurabh Shrivastava
Saurabh Shrivastava

Reputation: 1484

How to call a function as soon as widget is launched in Kivy

My app just have one button. I want to call a function as soon as widget is created/called. I have used init for the same.

My attempt:

#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')

from random import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from random import random
from random import choice
from kivy.properties import StringProperty
import time

Builder.load_string("""
<Highest>:
    GridLayout:
        cols: 1
        Button:
            id: btn_0
            text: "0"
            on_press: root.new()
""")

class Highest(Screen):
    def __init__(self,name):
        print "widget launched"
    def new(self):
        print "button pressed"


# Create the screen manager
sm = ScreenManager()
sm.add_widget(Highest(name='Highest'))

class TestApp(App):

    def build(self):
        return sm

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

On running, "widget launched" is displayed in consolde, but my application crashes with statement "python have stopped working". Please help.

Upvotes: 1

Views: 879

Answers (1)

inclement
inclement

Reputation: 29468

If you really want to detect instantiation, create your own Button subclass that calls the function in its __init__ method.

If that's not directly what you really want, there may be better alternatives.

Upvotes: 1

Related Questions