How do I make an exit button in npyscreen?

懵懂的女人 提交于 2020-12-05 21:59:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!