Search code examples
pythonnpyscreen

How do I make an exit button in npyscreen?


What I want is basically a regular npyscreen.Form, but I want the "OK" button to say "Exit".

It appears that you can't change the name of the button in the regular npyscreen.Form, so I tried subclassing npyscreen.ButtonPress:

import npyscreen

class ExitButton(npyscreen.ButtonPress):
    def whenPressed(self):
        self.parentApp.setNextForm(None)

class MainForm(npyscreen.FormBaseNew):
    def create(self):
        self.exitButton = self.add(ExitButton, name="Exit", relx=-12, rely=-3)

class App(npyscreen.NPSAppManaged):
    def onStart(self):
        self.addForm("MAIN", MainForm, name="My Form")

if __name__ == "__main__":
    app = App().run()

The button shows up, but when you click it, you get 'ExitButton' object has no attribute 'parentApp'.

Is there an easier way to do this?


Solution

  • Edwin's right, use self.parent.parentApp not self.parentApp.

    To exit the app use switchForm(None) instead of setNextForm(None).

    def whenPressed(self):
        self.parent.parentApp.switchForm(None)
    

    reference: a post by npyscreen's author confirms this works as expected.