简体   繁体   中英

Button' object has no attribute python callback

I want to have the callback function for the btn1 to change the player1.center_y and to interact with my program in general(changing values in the Gameclass).

However I get the error

' Button' object has no attribute 'player1 ' when the button is clicked. Is it because the instance class in wrong or something?.I am kind of new to OOP.

here is the relevant code:

class Gameclass(Widget):
    def on_touch_move(self, touch):
        if touch.x < self.width / 3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y

    def callback(self):
            self.player1.center_y = 22
            self.player2.center_y = 250

btn1 = Button(text='click me')
btn1.bind(on_press=Gameclass.callback)

My comment may be difficult to understand, so here is an example:

class Gameclass(Widget):
    def on_touch_move(self, touch):
        if touch.x < self.width / 3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y

    def callback(self, btn_instance):
            self.player1.center_y = 22
            self.player2.center_y = 250

btn1 = Button(text='click me')
gc = Gameclass()
btn1.bind(on_press=gc.callback)

Note that you probably create an instance of Gameclass somewhere else in your code, and that instance should be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM