Jens Wilken
Jens Wilken

Reputation: 31

how to send and use an widget's id from kivy to python

I am trying to disable buttons by id. Sending the id (pong) does not work, as I learned. However, for my final app I need to send letters A,B, ... F anyhow, so can I anyhow build up a string of the widget's id and use that to disable it? do I have to convert the string to another datatype? my .py

# main.py
from kivy.app import App
from kivy.uix.gridlayout import GridLayout


class TurboWidget(GridLayout):
    def ping(self, y):
        x = "btnStart"+y
        print(y)
        print(x)
        self.ids.x.disabled = True

    def pong(self, y):
        print(y)
        self.ids.y.disabled = True


class TurboApp(App):
    def build(self):
        return TurboWidget()


if __name__ == "__main__":
    TurboApp().run()

my .kv

# turbo.kv
<TurboWidget>
    cols: 2
    Button:
        id: btnStartA
        text:"A"
        on_release: root.Ping("A")

    Button:
        id: btnStartB
        text:"B"
        on_release: root.Ping("B")

    Button:
        id: btnStartC
        text:"C"
        on_release: root.Pong(btnStartC.id)
    Button:
        id: btnStartD
        text:"D"
        on_release: root.Pong(btnStartD.id)

Upvotes: 0

Views: 586

Answers (2)

New2Coding
New2Coding

Reputation: 191

You can do this by using the following method. Note that I am passing the ids as strings inside the method. Additionally I am using self.ids[y].disabled for setting the kivy attribute from the python side.

# main.py
from kivy.app import App
from kivy.uix.gridlayout import GridLayout

class TurboWidget(GridLayout):
    def ping(self, y):
        self.ids[y].disabled = True

    def pong(self, y):
        print(y)
        self.ids[y].disabled = True


class TurboApp(App):
    def build(self):
        return TurboWidget()


if __name__ == "__main__":
    TurboApp().run()

and by using the following kv file in the same folder as the main.py.

# turbo.kv
<TurboWidget>
    cols: 2
    Button:
        id: btnStartA
        text:"A"
        on_press: root.ping("btnStartA")

    Button:
        id: btnStartB
        text:"B"
        on_press: root.ping("btnStartB")

    Button:
        id: btnStartC
        text:"C"
        on_press: root.pong("btnStartC")

    Button:
        id: btnStartD
        text:"D"
        on_press: root.pong("btnStartD")

Upvotes: 1

Jens Wilken
Jens Wilken

Reputation: 31

self.ids.x.disabled= True

needs to be

self.ids[x].disabled= True

WITHOUT the dot.

https://kivy.org/doc/stable/guide/lang.html#accessing-widgets-defined-inside-kv-lang-in-your-python-code

Upvotes: 0

Related Questions