Python Forum
Help Returning to Different Menus
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help Returning to Different Menus
#1
Hello,

I have a login system that allows StandardUsers to login in and Admins to login.
If an Admin logs in and decides to view the inventory, the admin should return to the Admin Menu once complete.
If a StandardUser logs in and decides to view the inventory, the StandardUser should return to the Main Menu once complete, not the Admin Menu.

Right now I have it so everything returns the 'adminMenu()' once complete. How can I make it so depending on who is logged in (StanadardUser or Admin/SuperUser) it returns to the appropriate Menu?
(For example: Both Admins and StandardUsers can search for parts, and print the inventory report. But right now I have it just returning to the Admin Menu even if a StandardUser is logged in. So how do I get it to return to the appropriate menu depending on who is logged in. I've been struggling on this for a while, and I'm completely stuck. Any help is much appreciated).

Thanks in advance.

My full code:
#-----------------------------------------------
import os
from UserDatabase import *
import sqlite3
#---------------------------------------------------------------
                            #Overview
#---------------------------------------------------------------
#Run SQLiteDatabase-CreateTable.py to create the table
#TODO: Add a run once to run the CreateTable.py Script and if the table already exists, don't run the script. 

#User is prompted to a login screen 
#User enters thier name
#If their name is in the database they may access the program

#User is then taken to the main menu
#From there they can checkout a part,
#Return a part,
#Search for a part,
#And view all the parts in stock  

#Admins can:
#Add new items,
#Delete items,
#Update items,
#And view everything in stock
#TODO: Allow Main Menu to work Right now everything links to Admin Menu
#Allow Admin to create new private inventories
#---------------------------------------------------------------

#---------------------------------------------------------------
#                        Login Menu
#---------------------------------------------------------------
def login():
    while True:
        print('=============================\n''\tLogin\n''=============================')
        user = input("Enter your name (Case Sensitive): ")
        password = int(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:
        print('You are not registered to use this program')
        login()
#---------------------------------------------------------------

#---------------------------------------------------------------
#                          Main Menu 
#---------------------------------------------------------------
def mainMenu():
    print('=============================')
    print('= Inventory Management Menu =')
    print('=============================')
    print('(1) Checkout/Return Items in Inventory')
    print('(2) Search Item in Inventory')
    print('(3) Print Inventory Report')
    print('(4) Log Out')
    print('(Q) Quit')
    CHOICE = input("Enter choice: ")
    menuSelection(CHOICE)

def menuSelection(CHOICE):
    if CHOICE == '1':
        updateInventory()
    elif CHOICE == '2':
        searchInventory()
    elif CHOICE == '3':
        printInventory()
    elif CHOICE == '4':
        login()
    elif CHOICE == 'q' or CHOICE == 'Q':
        exit()
#---------------------------------------------------------------

#---------------------------------------------------------------
#                          Admin Menu 
#---------------------------------------------------------------
def adminMenu():
    print('=============================')
    print('= Inventory Admin Menu =')
    print('=============================')
    print('(1) Add New Item to Inventory')
    print('(2) Delete Item from Inventory')
    print('(3) Update Inventory')
    print('(4) Search Item in Inventory')
    print('(5) Print Inventory Report')
    print('(6) Log Out')
    print('(Q) Quit')
    CHOICE = input("Enter choice: ")
    adminMenuSelection(CHOICE)

def adminMenuSelection(CHOICE):
    if CHOICE == '1':
        addInventory()
    elif CHOICE == '2':
        removeInventory()
    elif CHOICE == '3':
        updateInventory()
    elif CHOICE == '4':
        searchInventory()
    elif CHOICE == '5':
        printInventory()
    elif CHOICE == '6':
        login()
    elif CHOICE == 'q' or CHOICE == 'Q':
        exit()
#---------------------------------------------------------------

#---------------------------------------------------------------
#                       Add Inventory Item 
#---------------------------------------------------------------
def addInventory():
    #Connect to the inventory database (inventory.db)
    connection = sqlite3.connect("inventory.db")
    cursor = connection.cursor()
 
    cursor = connection.cursor()

    cursor.execute('''
        insert into items (name, quantity, price, sell_price, description, category, location)
        values (?,?,?,?,?,?,?)
        ''', inserts())
    connection.commit()

    #Close the connection
    connection.close()
    adminMenu()

def inserts():
    name = input('Item Name: ')
    quantity = input("Item Quantity: ")
    price = float(input("Item Price $: "))
    sellPrice = price * 1.10
    description = input('Item Description: ')
    category = input('Item Category: ')
    location = input("Item Location: ")
    mylist = [name, quantity, price, sellPrice, description, category, location]
    return mylist

#---------------------------------------------------------------
#                 Remove/Delete Inventory Items 
#---------------------------------------------------------------
def removeInventory():

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

    print('=============================')
    print('= Delete From Inventory =')
    print('=============================')
    print('(1) Delete by ID')
    print('(2) Delete by Name')
    CHOICE = input("Enter choice: ")

    if CHOICE == '1':
        userQuery = input('Item ID: ')
        #Search by Category
        cursor.execute("DELETE FROM items WHERE id = ?",(userQuery,))
        connection.commit()
        print('The item with the ID: ' + userQuery + ' has been deleted.')

    elif CHOICE == '2':
        userQuery = input('Item Name (Must be exact name): ')
        #Search by Name
        cursor.execute("DELETE FROM items WHERE Name = ?",(userQuery,))
        connection.commit()
        print(userQuery + ' has been deleted.')

    #Close the connection to the database
    connection.close()
    #Go to Admin Menu
    adminMenu()

#---------------------------------------------------------------
#                 Update Inventory Items 
#---------------------------------------------------------------
def updateInventory():

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

    print('=============================')
    print('= Update From Inventory =')
    print('=============================')
    print("Find an item to update by entering it's ID or Name")
    print('(1) Update Item by ID')
    print('(2) Update Item by Name')
    CHOICE = input("Enter choice: ")

    #----- Update Item by ID -----
    #Choose Item to update by ID
    if CHOICE == '1':
        userQueryID = input('Item ID: ')

        #->Show info for the currently selected item
        cursor.execute('SELECT * FROM items WHERE ID = ?', (userQueryID,))
        result = cursor.fetchall()
        #Print Results/Info in rows
        print('\n--------------------')
        print('Current Info For Item: ' + userQueryID)
        print('--------------------')
        for row in result:
            print('\n--------------------')
            print("Item ID: ", row[0])
            print("Item Name: ", row[1])
            print("Item Quantity: ", row[2])
            print("Item Price: $", row[3])
            print("Item Sell Price: $", row[4])
            print("Item Description: ", row[5])
            print("Item Category: ", row[6])
            print("Item Location: ", row[7])
            print("Last Updated: ", row[10])
            print('--------------------\n')

        #-->Bring up update menu
        print('------------------------------')
        print("What would you like to update?")
        print('(1) Item Name')
        print('(2) Item Quantity')
        print('(3) Item Price')
        print('(4) Item Description')
        print('(5) Item Category')
        print('(6) Item Location')
        CHOICE = input("Enter choice: ")

        #Update Item Name
        if CHOICE == '1':
            userQuery = input('Enter new item name: ')
            cursor.execute("UPDATE items SET NAME = ? WHERE ID = ?",(userQuery, userQueryID,))
            connection.commit()
            print('The item name has been changed to: ' + userQuery)

        #Update Item Name
        elif CHOICE == '2':
            userQuery = input('Enter new item quantity: ')
            cursor.execute("UPDATE items SET Quantity = ? WHERE ID = ?",(userQuery, userQueryID,))
            connection.commit()
            print('The item quantity has been changed to: ' + userQuery)
        
        #Update Item Price
        elif CHOICE == '3':
            userQuery = input('Enter new item price: $')
            cursor.execute("UPDATE items SET Price = ? WHERE ID = ?",(userQuery, userQueryID,))
            connection.commit()
            print('The item price has been changed to: $' + userQuery)

        #Update Item Description
        elif CHOICE == '4':
            userQuery = input('Enter new item description: ')
            cursor.execute("UPDATE items SET Description = ? WHERE ID = ?",(userQuery, userQueryID,))
            connection.commit()
            print('The item description has been changed to: ' + userQuery)

        #Update Item Category
        elif CHOICE == '5':
            userQuery = input('Enter new item category: ')
            cursor.execute("UPDATE items SET Category = ? WHERE ID = ?",(userQuery, userQueryID,))
            connection.commit()
            print('The item category has been changed to: ' + userQuery)
        
        #Update Item Location
        elif CHOICE == '6':
            userQuery = input('Enter new item location: ')
            cursor.execute("UPDATE items SET Location = ? WHERE ID = ?",(userQuery, userQueryID,))
            connection.commit()
            print('The item location has been changed to: ' + userQuery)

    #----- Update Item by Name -----
    #Choose Item to update by Name
    elif CHOICE == '2':
        userQueryName = input('Item Name (Must be the exact name): ')

        #->Show info for the currently selected item
        cursor.execute('SELECT * FROM items WHERE NAME = ?', (userQueryName,))
        result = cursor.fetchall()
        #Print Results/Info in rows
        print('\n--------------------')
        print('Current Info For Item: ' + userQueryName)
        print('--------------------')
        for row in result:
            print('\n--------------------')
            print("Item ID: ", row[0])
            print("Item Name: ", row[1])
            print("Item Quantity: ", row[2])
            print("Item Price: $", row[3])
            print("Item Sell Price: $", row[4])
            print("Item Description: ", row[5])
            print("Item Category: ", row[6])
            print("Item Location: ", row[7])
            print("Last Updated: ", row[10])
            print('--------------------\n')

        print('------------------------------')
        print("What would you like to update?")
        print('(1) Item Name')
        print('(2) Item Quantity')
        print('(3) Item Price')
        print('(4) Item Description')
        print('(5) Item Category')
        print('(6) Item Location')
        CHOICE = input("Enter choice: ")

        #Update Item Name
        if CHOICE == '1':
            userQuery = input('Enter new item name: ')
            cursor.execute("UPDATE items SET NAME = ? WHERE ID = ?",(userQuery, userQueryName,))
            connection.commit()
            print('The item name has been changed to: ' + userQuery)

        #Update Item Name
        elif CHOICE == '2':
            userQuery = input('Enter new item quantity: ')
            cursor.execute("UPDATE items SET Quantity = ? WHERE ID = ?",(userQuery, userQueryName,))
            connection.commit()
            print('The item quantity has been changed to: ' + userQuery)
        
        #Update Item Price
        elif CHOICE == '3':
            userQuery = input('Enter new item price: $')
            cursor.execute("UPDATE items SET Price = ? WHERE ID = ?",(userQuery, userQueryName,))
            connection.commit()
            print('The item price has been changed to: $' + userQuery)

        #Update Item Description
        elif CHOICE == '4':
            userQuery = input('Enter new item description: ')
            cursor.execute("UPDATE items SET Description = ? WHERE ID = ?",(userQuery, userQueryName,))
            connection.commit()
            print('The item description has been changed to: ' + userQuery)

        #Update Item Category
        elif CHOICE == '5':
            userQuery = input('Enter new item category: ')
            cursor.execute("UPDATE items SET Category = ? WHERE ID = ?",(userQuery, userQueryName,))
            connection.commit()
            print('The item category has been changed to: ' + userQuery)
        
        #Update Item Location
        elif CHOICE == '6':
            userQuery = input('Enter new item location: ')
            cursor.execute("UPDATE items SET Location = ? WHERE ID = ?",(userQuery, userQueryName,))
            connection.commit()
            print('The item location has been changed to: ' + userQuery)

    #Close the connection to the database
    connection.close()
    #Go to Admin Menu
    adminMenu()

#---------------------------------------------------------------
#                     Search Inventory Items 
#---------------------------------------------------------------
def searchInventory():

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

    print('=============================')
    print('= Search Inventory =')
    print('=============================')
    print('(1) Search by Name')
    print('(2) Search by Category')
    CHOICE = input("Enter choice: ")

    if CHOICE == '1':
        userQuery = input('Item Name: ')
        #Search by Name
        cursor.execute("select * from items WHERE Name LIKE'%'||?||'%'",(userQuery,))

    elif CHOICE == '2':
        userQuery = input('Item Category: ')
        #Search by Category
        cursor.execute("select * from items WHERE Category LIKE'%'||?||'%'",(userQuery,))
    
    #Get all info from the Items Table
    result = cursor.fetchall()

    #Print Results/Inventory in rows
    print('\n--------------------')
    print('Search Results')
    print('--------------------')

    for row in result:
        print('\n')
        print('--------------------')
        print("Item ID: ", row[0])
        print("Item Name: ", row[1])
        print("Item Quantity: ", row[2])
        print("Item Price: $", row[3])
        print("Item Sell Price: $", row[4])
        print("Item Description: ", row[5])
        print("Item Category: ", row[6])
        print("Item Location: ", row[7])
        print("Last Updated: ", row[10])
        print('--------------------')

    #Close the connection to the database
    connection.close()
    #Go to Admin Menu
    adminMenu()

#---------------------------------------------------------------
#                      Print Inventory Items 
#---------------------------------------------------------------
def printInventory():
    #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()

    #Print Results/Inventory in rows
    print('\n--------------------')
    print('Inventory Report')
    print('--------------------')
    for row in result:
        print('\n')
        print('--------------------')
        print("Item ID: ", row[0])
        print("Item Name: ", row[1])
        print("Item Quantity: ", row[2])
        print("Item Price: $", row[3])
        print("Item Sell Price: $", row[4])
        print("Item Description: ", row[5])
        print("Item Category: ", row[6])
        print("Item Location: ", row[7])
        print("Last Updated: ", row[10])
        print('--------------------')

    #Close the connection to the database
    connection.close()
    #Go to Admin Menu
    adminMenu()

#---------------------------------------------------------------
#                    Countinue/Exit Function
#---------------------------------------------------------------
#TODO: If user is a StandardUser countinue to Main Menu
#And if user is an Admin countinue to Admin Menu
def countinueOrExit():
    CHOICE = input('Enter C to continue or press any button to exit: ')
    if CHOICE == 'c' or CHOICE == 'C':
            mainMenu()
    else:
        exit()
#---------------------------------------------------------------
#---------------------------------------------------------------

#---------------------------------------------------------------
#                 Start Program
#---------------------------------------------------------------
#Start Program on login screen
login()
#---------------------------------------------------------------
Reply
#2
(May-07-2022, 12:45 AM)Extra Wrote: How can I make it so depending on who is logged in (StanadardUser or Admin/SuperUser) it returns to the appropriate Menu?
The way you made it you do not return to a menu, instead you start a new menu because you end most of your functions with adminMenu(). You should end the function just with "return" and make the menu repeating. Also you have the printing of the menu separated from inputting the choice. That makes it more difficult. Also you are using "exit()" to end the program. This is not needed when you just use "return".
A small example of what I mean:
def adminMenu():
    while True:    # Keep showing the menu until user wants to quit.
        print('=============================')
        print('= Inventory Admin Menu =')
        print('=============================')
        print('(1) Add New Item to Inventory')
        print('(2) Delete Item from Inventory')
        print('(3) Update Inventory')
        print('(4) Search Item in Inventory')
        print('(5) Print Inventory Report')
        print('(Q) Quit')
        CHOICE = input("Enter choice: ")
        if CHOICE == '1':
            addInventory()
        elif CHOICE == '2':
            removeInventory()
        elif CHOICE == '3':
            updateInventory()
        elif CHOICE == '4':
            searchInventory()
        elif CHOICE == '5':
            printInventory()
        elif CHOICE == 'q' or CHOICE == 'Q':
            break    # Stop repeating the menu.
    return    # Return to the previous level
#---------------------------------------------------------------
def addInventory():
    #Connect to the inventory database (inventory.db)
    connection = sqlite3.connect("inventory.db")
    cursor = connection.cursor()
  
    cursor = connection.cursor()
 
    cursor.execute('''
        insert into items (name, quantity, price, sell_price, description, category, location)
        values (?,?,?,?,?,?,?)
        ''', inserts())
    connection.commit()
 
    #Close the connection
    connection.close()
    # adminMenu()    # Don't do this.
    return    # Return to the calling menu.
Reply
#3
As ibreeden said, you cannot recursively call functions in your GUI. You should avoid using recursion at all unless you are trying to solve a problem that requires a recursive solution. As written, your program will slowly consume memory until it hits the recursion limit in Python and crash. Instead of recursion you should have a base function that calls all the other functions. You might be close to such a solution if you remove the adminMenu() call at the end of all your functions and put a loop in you mainMenu().

You also need to fix the login recursion. login() can call validate, but validate cannot call login(). Again this will require putting a loop in login().
Reply
#4
Thanks.
Both your inputs helped me understand what I was doing wrong.
I was able to get it working using return(Thanks for bring that up by the way. It was a big help), now I'll look into updating my login() so I don't have the login recursion.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  installing anaconda3 fails (failed to create menus) Hikki 9 4,311 Feb-10-2022, 06:49 PM
Last Post: snippsat
  Contextual pop-up menus in Sublime Text Mondata 4 2,472 Apr-08-2020, 06:32 PM
Last Post: buran

Forum Jump:

User Panel Messages

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