Home > Blockchain >  How can we check if an image exists inside a button in python's kivy library?
How can we check if an image exists inside a button in python's kivy library?

Time:07-21

So the problem I am having is that I have placed an image inside my button object in my .kv file and I want to check that if an image exists inside the button. Now the problem here is that they both are widgets (one inside the other) so my instance method isn't working. Below is my code.

GridLayout:
    id: chess_board
    cols: 8
    rows: 8
    padding: ("60dp", "60dp", "60dp", "60dp")
    orientation: 'tb-lr'
    
    Button:
        id: button_1
        background_normal: ''
        background_color: (1,1,1,1)
        on_press: app.moves(self)

        AsyncImage:
            id: white_1
            source: 'imgs/WhiteCastle.png'
            center_x: self.parent.center_x
            center_y: self.parent.center_y

So now I want to check if an AsyncImage exists in a button because in some other buttons that I have created it does not exist. Can someone plzzz help. Below is my .py file.

def moves(self, instance):
    all_ids = instance.parent.parent.ids.items()
    id = self.get_id(instance)
    print(id)

def get_id(self, instance):
    for id, widget in instance.parent.parent.ids.items():
        if widget.__self__ == instance:
            return id

CodePudding user response:

If you change the moves() method a bit, like this:

def moves(self, instance, root):
    if 'white_1' in root.ids:
        asyncImage = root.ids.white_1
        if asyncImage in instance.children:
            print('Button contains an AsyncImage')
            return
    print('Button does not contain an AsyncImage')

And change the kv:

    on_press: app.moves(self)

to:

    on_press: app.moves(self, root)
  • Related