How to assign a function to a kivy button?

Asked

Viewed 55 times

0

I am a beginner in python and I want that whenever a certain button is pressed, run a function. Here is the code:

application py.

import kivy
kivy.require("1.8.0")

from kivy.app import App

class application(App):
    def printar(self):
        print("Hello World")
        
application().run()

application.Kv

BoxLayout:
    orientation: "vertical"
    BoxLayout:
        spacing: 130
        padding: [30, 30, 30, 30]
        size_hint: [1, .1]
        orientation: "horizontal"
        
        Button:
            id: option
            text: "Options"
            
        Label:
            text: "Connected"
            bold: True
            color: [0, 1, 0, .8]
            font_name: "DejaVuSans"
            
        Button:
            id: onoff
            text: "On/Off"
            
    BoxLayout:
        orientation: "horizontal"
        spacing: 20
        padding: [30, 30, 30, 30]
        
        TextInput:
            size_hint: [.7, .05]
            pos_hint: {"y": .5}
            multiline: False
            hint_text: "Write"
        
        Button:
            id: send
            text: "Send"
            size_hint: [.2, .05]
            pos_hint: {"y": .5}
            on_release: root.printar()

1 answer

1


def printar(self):
   print("ação")


Button:
    id: option
    text: "Options"
    on_press: root.printar()

Whenever there is an action on the button the function called printar() will be started, if only call the function "printar()" will not be found you have to make reference to the instance.

Can do the specification part directly in python code which layout type:

import kivy
kivy.require("1.8.0")

from kivy.app import App
from kivy.uix.boxLayout import BoxLayout


class Programa(BoxLayout):
    def printar(self):
       print("inicado")

class application(App):
    pass
        

iniciar.application()
iniciar.run()




<Programa@BoxLayout>:
    orientation: "vertical"
    ...resto do código
        
        Button:
            id: option
            text: "Options"
            on_press: root.printar()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.