问题
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?
回答1:
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.
回答2:
It is not the most elegant solution but it works, first of all to access setNextForm from ExitButton you should do it as follows: self.parent.parentApp.setNextForm(None). Even correcting this does not work, I used sys.exit(0) to exit.
import npyscreen
import sys
class ExitButton(npyscreen.ButtonPress):
def whenPressed(self):
sys.exit(0)
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()
回答3:
There is a way to change the name of the OK Button. Modify in the desired form class the attribute
OK_BUTTON_TEXT='YourCustomNameOKButton'
Reference: built-in help for FORM class.
回答4:
use self.parent.parentApp since ExitButton resides inside the Form, and Form has access to parentApp
use switchForm() instead of setNextForm()
class ExitButton(npyscreen.ButtonPress):
def whenPressed(self):
self.parent.parentApp.switchForm(None)
来源:https://stackoverflow.com/questions/41515278/how-do-i-make-an-exit-button-in-npyscreen