odiocsi
odiocsi

Reputation: 15

How to print the pressed button name in kivy

I am new to kivy and I "generated" 20 buttons and I want to print the name of the buttons with the function called "on_press_kartya" when they are pressed but I don't know how can I do that. I would appreciate any help.

from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import random

class MainApp(App):
    def build(self):
        self.startbutton = Button(text='Start',
                        size_hint=(.2, .2),
                        pos_hint={'center_x': .5, 'center_y': .5})
        self.startbutton.bind(on_press=self.on_press_startbutton)

        boxlayout = BoxLayout()
        boxlayout.add_widget(self.startbutton)
        return boxlayout

    def on_press_startbutton(self, instance):
        self.root.remove_widget(self.startbutton)
        self.root.add_widget(self.visszabutton)
        start()
        for i in range(20):
            self.root.add_widget(Button(text=str(i), on_press=lambda *args: self.on_press_kartya(text)))

    def on_press_kartya(self, instance):
        print("the name of the pressed button")

Upvotes: 0

Views: 413

Answers (1)

ApuCoder
ApuCoder

Reputation: 2908

Since your method on_press_kartya is an event callback you just pass the instance (here Button) and access its properties therein as,

    def on_press_startbutton(self, instance):
        ...
        for i in range(20):
            #self.root.add_widget(Button(text=str(i), on_press=lambda *args: self.on_press_kartya(text)))
            self.root.add_widget(Button(text=str(i), on_press=self.on_press_kartya))

    # Then in the callback,
    def on_press_kartya(self, instance):
        print("the name of the pressed button", instance.text)

Also if you use lambda or partial to pass some arg(s) you may need some extra arg(s) as well in the callback.

Upvotes: 1

Related Questions