Python Forum
Help with passing values in npyscreen
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with passing values in npyscreen
#1
Hello,

I'm playing around with npyscreen to make my terminal application look nicer and be more user friendly.
I'm trying to take in the user's input from self.user and seld.password and carry them over to my validate function so it can go to the menu screen.

Am I passing the values correctly? If not, how do I?

Thanks I advance.

TUITest.py
import npyscreen

class LoginForm(npyscreen.Form):
    def afterEditing(self):
        self.parentApp.setNextForm(None)

    def create(self):
        self.user = self.add(npyscreen.TitleText, name='Name:')
        self.password = self.add(npyscreen.TitleText, name='Password:')

        user = self.user
        password = self.password
       validate(user,password)


class MyApplication(npyscreen.NPSAppManaged):
   def onStart(self):
       self.addForm('MAIN', LoginForm, name='Log In')

if __name__ == '__main__':
   TestApp = MyApplication().run()
My Validate Function
#---------------------------------------------------------------
#                Validate Function -> Validates user 
#---------------------------------------------------------------
#Pass in user and password variables from login function
#Check if the user is valid (registered in database) -> Give access to inventory program
#close login screen and open menu screen 
#If user is not valid -> return to login or have invalid credentials popup
#-->TODO: Write the user and current date to a file to keep track of logins
def validate(user, password):
    if StandardUsers().get(user) == password:
        print('Success! You are now logged in as: ' + user)
        #mainMenu()
        return True

    if SuperUsers().get(user) == password:
        print('Success! You are now logged in as: ' + user)
        #adminMenu()
        
    else:
        return
#---------------------------------------------------------------
Side notes:
This was my working terminal version and I want to carry it over to npyscreen so it looks nicer.
This is what I'm trying to achieve but with a fancy TUI

#---------------------------------------------------------------
#                        Login Menu
#---------------------------------------------------------------
def login():
    while True:
        print('=============================\n''\tLogin\n''=============================')
        user = input("Enter your name (Case Sensitive): ")
        password = input("Enter your password: ")
        #If the credentials are validated -> Run validate function -> Go to according menu
        #Else -> Print error message and show login screen again
        if validate(user, password):
            break
        else:
            print('You are not registered to use this program')
#---------------------------------------------------------------

#---------------------------------------------------------------
#                Validate Function -> Validates user 
#---------------------------------------------------------------
#Pass in user and password variables from login function
#Check if the user is valid (registered in database) -> Give access to inventory program 
#If user is not valid -> return to login
#-->TODO: Write the user and current date to a file to keep track of logins
def validate(user, password):
    if StandardUsers().get(user) == password:
        print('Success! You are now logged in as: ' + user)
        mainMenu()
        return True

    if SuperUsers().get(user) == password:
        print('Success! You are now logged in as: ' + user)
        adminMenu()
        
    else:
        return
#---------------------------------------------------------------
Reply
#2
Again you do not use the "return" keyword very well.
Your validate() function returns "True" if it is a standard user, and "None" if it is an admin user or invalid user. Consider returning values like "user", "admin" or "incorrect". Then you can use these values to let the calling function decide what to do. (mainMenu(), adminMenu() or ask credentials again.)
Reply
#3
Ok, I'll fix my return statement, but the problem I have now is when I print the user for testing purposes:
    def create(self):
            self.user = self.add(npyscreen.TitleText, name='Name:')
            self.password = self.add(npyscreen.TitleText, name='Password:')

            user = self.user
            password = self.password
            print(user)
I get this:
Error:
<npyscreen.wgtitlefield.TitleText object at 0x000001EB05A9AF70>
Why did I get this and how can I fix it?
(For that test I typed in "Bob" as the user and got all that, instead of the string "Bob")
Reply
#4
What happens if you print name.value ?
Reply
#5
Nothing because name is not defined.
Error:
print(name.value) NameError: name 'name' is not defined
If I do: user.value I get:
Output:
None
No matter what I type in for the user.
Reply
#6
(May-14-2022, 02:25 PM)Extra Wrote: I'm playing around with npyscreen to make my terminal application look nicer and be more user friendly.
The project is dead,and the screenshots dos not look good at all.
npyscreen issues Wrote:The latest release on PyPI doesn't work on versions above 3.6 (possibly 3.7).
Look at a modern way with Rich and Textual,the fantastic work of Will McGugan✨
Reply
#7
(May-20-2022, 12:29 AM)snippsat Wrote: Look at a modern way with Rich and Textual,the fantastic work of Will McGugan✨

This looks amazing! I had no clue this existed, thanks for introducing me to it. I'm definitely going to play around with both Rich and Textual now.
Reply
#8
Now I downloaded Rich and I'm trying to put my inventory.db into a table.

I have this:
from rich.console import Console
from rich.table import Table
import sqlite3

#Connect to the inventory database (inventory.db)
connection = sqlite3.connect("inventory.db")
cursor = connection.cursor()

cursor = connection.cursor()
#Display all records in the Items Table:
cursor.execute('select * from items')

#Get all info from the Items Table
result = cursor.fetchall()

table = Table(title="Item Display")

table.add_column("Name", justify="right", style="cyan", no_wrap=True)
table.add_column("Quantity", style="magenta")
table.add_column("Price($)", justify="right", style="green")
table.add_column("Sell Price($)", justify="right", style="blue")

for row in result:
    table.add_row(row[1],row[2],row[3],row[4])

connection.close()

console = Console()
console.print(table)
But when I run it I get this error:
Error:
line 460, in add_row raise errors.NotRenderableError( rich.errors.NotRenderableError: unable to render int; a string or other renderable object is required
The reason I get this error is because I take in Quantity and Price as an INT. I need those values to be INTs because I do caluclations with them later on.

My question is, how do I work around this error, so I can display my Quantity, Price, and Sell_Price?

Thanks.




This is my CreateTable.py so you can see how my inventory.db is formatted :
import sqlite3

def createDatabase():
        #Create a database (inventory.db)
        connection = sqlite3.connect("inventory.db")
        cursor = connection.cursor()

        table = """CREATE TABLE IF NOT EXISTS Items
                (ID INTEGER PRIMARY KEY  AUTOINCREMENT,
                NAME           TEXT    NOT NULL,
                Quantity       INT     NOT NULL,
                Price          DOUBLE  NOT NULL,
                Sell_Price     DOUBLE,
                Description    TEXT,
                Category       TEXT,
                Location       TEXT    NOT NULL,
                Length_Ft      INT,
                Barcode        INT,
                Image          BLOB,
                Date Updated   datetime default current_timestamp);"""

        #Execute the creation of the table
        cursor.execute(table)
        #print("The database has been created")
        #Commit the changes
        connection.commit()
        #Close the connection
        connection.close() 
Reply
#9
Never mind.

Did:
 table.add_row(row[1], str(row[2]), str(row[3]))
And it worked.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Solved]Return values from npyscreen Extra 2 1,093 Oct-09-2022, 07:19 PM
Last Post: Extra
  Passing Values of Dictionaries to Function & Unable to Access Them firebird 3 2,530 Aug-03-2019, 10:25 PM
Last Post: firebird

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020