简体   繁体   中英

TypeError: method()takes in 1 positional argument but 2 were given (Python and Kivy)

Im trying to use a function inside my py file to change screens after a certain number of seconds, these are the 2 screens and the ScreenManager(although not all the code,shortened it to the important bits):

class StartScreen(Screen):
    pass

class Buttons(Screen):

    def change_screen(self):
        WindowManager.current = "start_screen"


class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("my.kv")

class MyApp(App):

    def build(self):
        return kv


if __name__ == '__main__':
    Window.fullscreen = "auto"
    MyApp().run()

and this is the whole kv file:

#:import NoTransition kivy.uix.screenmanager.NoTransition
#:import Clock kivy.clock.Clock

WindowManager:
    transition: NoTransition()

    StartScreen:
    Buttons:


<StartScreen>:
    name: "start_screen"

    Button:
        background_normal: "maxresdefault.jpg"
        background_down: "maxresdefault.jpg"
        size_hint: 0.3, 0.3
        pos_hint: {"x": .35, "y": .35}
        text: "Play"
        font_size: 250
        on_release:
            app.root.current = "btn_screen"
            root.reset_score()


<Buttons>:
    name: "btn_screen"
    btn: btn
    on_enter:
        Clock.schedule_once(root.change_screen, 5)

    Button:
        background_normal: "pepe11.png"
        background_down: "pepe11.png"
        id: btn
        size_hint: 0.2, 0.3
        pos_hint: {"x": .4, "y": .35}
        on_press:
            root.respawn()

and so my problem is with the Clock.schedule_once command I try to call when entering the Buttons screen, I just keep getting "TypeError: change_screen() takes 1 positional argument but 2 were given".

Thank you all in advance.

You have 2 errors:

  1. Clock.schedule_once() passes as an argument the time interval to the callback so you must pass an additional parameter.

  2. WindowManager.current is not valid because current is not a static attribute so you must access it through an object, in the Screen case you can access the ScreenManager that manages it through the manager property.

So the solution is:

# ...
class Buttons(Screen):
    def change_screen(self, dt):
        self.manager.current = "start_screen"
# ...

Clock uses the dt argument (delta-time) for the callback function.
You have to change your function like this:

def change_screen(self, dt):
    WindowManager.current = "start_screen"

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