Advertisement
BabbaYagga

GUI app using Tkinter

May 14th, 2024
168
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.40 KB | Help | 0 0
  1. #----------------
  2. # --- main.py ---
  3. #----------------
  4.  
  5. import tkinter as tk
  6. from tkinter import ttk, messagebox
  7. import re
  8. import locale
  9. from businesslogic import BusinessLogic
  10. from dataaccesslayer import DataAccessLayer
  11.  
  12. def main():
  13.    
  14.     # create main window
  15.     window = tk.Tk()
  16.     window.title('Create new account...')
  17.     window.geometry('600x225')
  18.     window.minsize(600, 225)
  19.  
  20.     # create an instance of the BusinessLogic & DataAccessLayer classes
  21.     bl = BusinessLogic(window)
  22.     dal = DataAccessLayer(window)
  23.  
  24.     def createAccount():    #routingNumber, accountNumber, openingDeposit):
  25.         routingNumber = txtRoutingNumber.get()
  26.         accountNumber = txtAccountNumber.get()
  27.         openingDeposit = formatAsCurrency(float(txtOpeningDeposit.get()))
  28.  
  29.         # dal.insertNewAccount()
  30.        
  31.         print(f"\nCreating new account...\n"
  32.               f"\tRouting #: {routingNumber}\n"
  33.               f"\tAccount #: {accountNumber}\n"
  34.               f"\t  Deposit: {formatAsCurrency(openingDeposit)}\n\n")
  35.  
  36.         return True
  37.  
  38.     def formatAsCurrency(amount):
  39.         return '{:.2f}'.format(float(amount))
  40.  
  41.     # create label/prompt for the routing number
  42.     lblRoutingNumber = ttk.Label(window,
  43.                                 text="ABA routing number: ",
  44.                                 justify="right",
  45.                                 borderwidth=0,
  46.                                 font="Tahoma 12",
  47.                                 relief="solid")
  48.  
  49.     lblRoutingNumber.place(x=85, y=42)
  50.  
  51.     # create entry box for routing number
  52.     txtRoutingNumber = ttk.Entry(
  53.         window,
  54.         validate="key",
  55.         width=10,
  56.         justify="left",
  57.         name="routingNumber",
  58.         font="Tahoma 12",
  59.         validatecommand=(window.register(bl.validateRoutingNumber),
  60.                         '%S',  # character(s) just entered or deleted
  61.                         '%s',  # text already in the textbox, before any changes
  62.                         '%P',  # text in the textbox if the insertion/deletion is allowed
  63.                         '%d',  # action code, see above
  64.                         "txtRoutingNumber",
  65.                         9  # maximum number of digits allowed
  66.                         )
  67.     )
  68.  
  69.     txtRoutingNumber.place(x=307, y=40)
  70.  
  71.     # create label/prompt for the account number
  72.     lblAcctNumber = ttk.Label(window,
  73.                             text="Account number: ",
  74.                             justify="right",
  75.                             borderwidth=0,
  76.                             font="Tahoma 12",
  77.                             relief="solid")
  78.  
  79.     lblAcctNumber.place(x=124, y=82)
  80.  
  81.     # create entry object for the account number
  82.     txtAccountNumber = ttk.Entry(window,
  83.                                 validate="key",
  84.                                 width=19,
  85.                                 justify="left",
  86.                                 name="accountNumber",
  87.                                 font="Tahoma 12",
  88.                                 validatecommand=(window.register(bl.validateInputIsDigit), '%S', False)  #, '%W', 9, 18)
  89.                                 )
  90.  
  91.     txtAccountNumber.place(x=307, y=80)
  92.  
  93.     # create label/prompt for the opening deposit
  94.     lblOpeningDeposit = ttk.Label(window,
  95.                                 text="Opening deposit: $",
  96.                                 justify="right",
  97.                                 borderwidth=0,
  98.                                 font="Tahoma 12",
  99.                                 relief="solid")
  100.  
  101.     lblOpeningDeposit.place(x=111, y=122)
  102.  
  103.     # create entry object for the opening deposit
  104.     txtOpeningDeposit = ttk.Entry(window,
  105.                                 validate="key",
  106.                                 width=10,
  107.                                 justify="left",
  108.                                 name="openingDeposit",
  109.                                 font="Tahoma 12",
  110.                                 validatecommand=(window.register(bl.validateIsCurrency), '%S', '%s', '%P', True)
  111.                                 )
  112.  
  113.     txtOpeningDeposit.place(x=307, y=120)
  114.  
  115.     # create "Submit" button
  116.     btnOK = ttk.Button(window,
  117.                     name="btnOK",
  118.                     text="Submit",
  119.                     width=10,
  120.                     command=createAccount(),    #createAccount())
  121.                     ).place(x=80, y=180)
  122.  
  123.     # create "Cancel" button
  124.     btnCancel = ttk.Button(window,
  125.                         name="btnCancel",
  126.                         text="Cancel",
  127.                         width=10,
  128.                         command=window.destroy
  129.                         ).place(x=400, y=180)
  130.  
  131.     # set initial focus to the ABA routing number Entry() widget
  132.     txtRoutingNumber.focus()
  133.  
  134.     # run ininite loop
  135.     window.mainloop()
  136.  
  137. # EOFunc main()
  138.  
  139. if __name__ == "__main__":
  140.     main()
  141.  
  142. #-------------------------
  143. # --- businesslogic.py ---
  144. #-------------------------
  145.  
  146. import tkinter as tk
  147. from tkinter import ttk, messagebox
  148. import re
  149. import locale
  150.  
  151. class BusinessLogic:
  152.  
  153.     def __init__(self, parentGUI):
  154.         self.parent = parentGUI
  155.  
  156.     def validateRoutingNumber(self,
  157.                             inputText,    # text that was entered or deleted
  158.                             currentText,  # text that currently in the textbox, *before* any change
  159.                             proposedText, # text that will be in the textbox, *if* the change is allowed
  160.                             actionCode,   # see block comment abovew
  161.                             widgetName,   # name of the widget object
  162.                             maxLength):   # maximum number of digits
  163.  
  164.         # if number of digits currently in the textbox is less than the maximum length...
  165.         if (len(proposedText) < int(maxLength)):
  166.  
  167.             # make sure text entered is a digit, not a character
  168.             if (inputText.isdigit()):
  169.                 return True
  170.             else:
  171.                 return False
  172.            
  173.         # length of text currently in the textbox is -eq or -gt the maximum length
  174.         else:
  175.            
  176.             if (len(proposedText) > int(maxLength)):
  177.                 return False
  178.  
  179.             if (self.isValidRoutingNumber(proposedText)):
  180.                 return True   # accept the input
  181.             else:
  182.                 return False  # reject it
  183.  
  184.         return
  185.  
  186.     def isValidRoutingNumber(self, routingNumber):
  187.         n = 0
  188.  
  189.         for i in range(0, len(str(routingNumber)), 3):
  190.            
  191.             n += int(str(routingNumber)[i]) * 3 + \
  192.                  int(str(routingNumber)[i+1]) * 7 + \
  193.                  int(str(routingNumber)[i+2])
  194.  
  195.         if (n != 0 and n % 10 == 0):
  196.             #print(f"{routingNumber} is a valid ABA routing number.")
  197.             # messagebox.showinfo("Information", f"\"{routingNumber}\" is a valid ABA routing number.")
  198.             # print(f"Routing number {routingNumber} is valid")
  199.             return True
  200.         else:
  201.             print(f"{routingNumber} is *not* a valid ABA routing number!")
  202.             # messagebox.showerror("Error", f"\"{routingNumber}\" is not a valid ABA routing number!")
  203.             return False
  204.  
  205.         return
  206.  
  207.     def validateInputIsDigit(self,
  208.                             insertText,
  209.                             acceptDecimalPoint):
  210.  
  211.         if (acceptDecimalPoint and insertText == "."):
  212.             return True
  213.         else:
  214.             if insertText.isdigit():
  215.                 return True
  216.             else:
  217.                 return False
  218.  
  219.     def isValidAccountNumber(accountNumber):
  220.         if accountNumber is None:
  221.             return False
  222.         else:
  223.             regEx = r'^[0-9]{9,18}$'  # account number must be contain between 9 and 18 digits
  224.  
  225.             if re.match(regEx, accountNumber):
  226.                 return True
  227.             else:
  228.                 return False
  229.  
  230.         return
  231.  
  232.     def validateIsCurrency( self,
  233.                             userInput,              # amount that was entered or deleted
  234.                             currentAmount,          # amount that's currently in the textbox, *before* any change
  235.                             proposedAmount,         # amount that will be in the textbox, *if* the change is allowed
  236.                             acceptDecimal = True,   # accept a decimal point?
  237.                             acceptMinus = False):   # accept a minus sign?
  238.  
  239.         charsToReject = [",", "$", "."]
  240.  
  241.         if not acceptMinus:
  242.             charsToReject.append("-")
  243.  
  244.         if acceptDecimal:
  245.             charsToReject.remove(".")
  246.  
  247.         # TODO: add currency symbol for the user's locale
  248.  
  249.         if (userInput in charsToReject):
  250.             return False
  251.        
  252.         # if the *proposed* amount already contains a decimal point...
  253.         if ("." in proposedAmount):
  254.            
  255.             # and it would have more than 2 decimal places should the insertion/deletion be accepted
  256.             if (len(str(proposedAmount).split(".")[1]) > 2):
  257.                 return False
  258.  
  259.         if (acceptDecimal and userInput == "."):
  260.  
  261.             # if the proposed amount would contain more than 1 decimal point
  262.             if (proposedAmount.count(".") > 1):
  263.                 return False
  264.  
  265.             return True
  266.        
  267.         else:
  268.  
  269.             if (self.isValidCurrency(proposedAmount)):
  270.                 return True
  271.             else:
  272.                 return False
  273.            
  274.     def isValidCurrency(self, amount):
  275.         rePattern = r'^[1-9]\d*(\.\d{1,2})?$'
  276.  
  277.         try:
  278.             if re.match(rePattern, "{:.2f}".format(float(amount))):
  279.                 return True
  280.             else:
  281.                 return False
  282.         except:
  283.             return False
  284.  
  285.         return
  286.  
  287. #---------------------------
  288. # --- dataaccesslayer.py ---
  289. #---------------------------
  290.  
  291. #import re
  292. #import locale
  293.  
  294. # TODO: Implement Sqlite
  295. class DataAccessLayer:
  296.  
  297.     def __init__(self, parentGUI):
  298.         self.parent = parentGUI
  299.         pass
  300.  
  301.     # stub function until Sqlite is implemented
  302.     def insertNewAccount(self):
  303.         routingNumber = self.parent.txtRoutingNumber.get(),
  304.         accountNumber = self.parent.txtAccountNumber.get()
  305.         openingDeposit = self.parent.txtOpeningDeposit.get()
  306.        
  307.         print(f"\nCreating new account...\n"
  308.         f"\tRouting #: {routingNumber}\n"
  309.         f"\tAccount #: {accountNumber}\n"
  310.         f"\t  Deposit: ${openingDeposit}\n\n")
  311.  
  312.  
  313.    
  314.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement