Add Money

Add Money

Above UI we are going to create by Tkinter for adding money in our Expense management system desktop application. For that first we create a window and configure its title, size and color. Here we are creating a window at Top Level so we can add this window at the top of any other window.

    
    root = tk.Toplevel()


    root.title("Add Money")

    root.configure(bg="#585858")
    root.resizable(width=0, height=0)
    win_width = 1280
    win_height = int(1280 * 56.25 / 100)
    root.geometry(str(win_width) + "x" + str(win_height))

    # Get screen size
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    Util.set_font_size(screen_width, screen_height, win_width, win_height)

    self.width = win_width * 96 / 100
    self.height = win_height * 94 / 100
    

After creation of window, we will add a canvas background.

    
    bg_canvas = RoundBackgroundFrame(root, self.width, self.height, padding, cornerradius, self.color, "#585858")
    bg_canvas.place(width=self.width, height=self.height, x=win_width / 2 - self.width / 2,y=win_height / 2 - self.height / 2)
    class RoundBackgroundFrame(tk.Canvas):

    def __init__(self, parent, width, height, padding, cornerradius, color, bg):
        tk.Canvas.__init__(self, parent, borderwidth=0, relief="flat", highlightthickness=0, bg=bg)
        self.width = width
        self.height = height
        self.padding = padding
        self.cornerradius = cornerradius
        self.color = color

        original = Image.open("images/corner.png")
        resized = original.resize((int(40), int(40)), Image.ANTIALIAS)
        self.image_r_t = ImageTk.PhotoImage(resized)

        original = original.rotate(90, expand=0)
        resized = original.resize((int(40), int(40)), Image.ANTIALIAS)
        self.image_l_t = ImageTk.PhotoImage(resized)

        original = original.rotate(90, expand=0)
        resized = original.resize((int(40), int(40)), Image.ANTIALIAS)
        self.image_l_b = ImageTk.PhotoImage(resized)

        original = original.rotate(90, expand=0)
        resized = original.resize((int(40), int(40)), Image.ANTIALIAS)
        self.image_r_b = ImageTk.PhotoImage(resized)

        self.shape(width, height, padding, cornerradius, color)
        (x0, y0, x1, y1) = self.bbox("all")
        width = (x1 - x0)
        height = (y1 - y0)
        self.configure(width=width, height=height)

    def shape(self, width, height, padding, cornerradius, color):
        self.create_polygon((padding, height - cornerradius - padding, padding, cornerradius + padding,
                                    padding + cornerradius, padding, width - padding - cornerradius, padding,
                                    width - padding, cornerradius + padding, width - padding,
                                    height - cornerradius - padding, width - padding - cornerradius, height - padding,
                                    padding + cornerradius, height - padding), fill=color, outline=color)

        self.create_image(width - self.image_r_t.width(), 0, image=self.image_r_t, anchor=NW)
        self.create_image(0, 0, image=self.image_l_t, anchor=NW)
        self.create_image(0, height - self.image_l_b.width(), image=self.image_l_b, anchor=NW)
        self.create_image(width - self.image_r_b.width(), height - self.image_r_b.width(), image=self.image_r_b, anchor=NW)



    

Once your window is created with custom background, we will create a frame with some reduced dimensions.

    
    self.width = self.width * 98 / 100
    self.height = self.height * 96 / 100
    self.base_frame = Frame(root,width=self.width, height=self.height, bg=self.color)
    bg_canvas.create_window(self.width / 100, self.height * 2 / 100, anchor=NW, window=self.base_frame)

    #Add Heading
    add_heading_label(self.base_frame, self.color, AppConstant.FONT_SIZE, self.height, self.width, root)

    def add_heading_label(base_frame, color, font_size, height, width, root):
        label_heading = Label(base_frame, text="Add Money", anchor=CENTER, bg=color, font=("Lucida Grande", font_size + 6))
        label_heading.place(width=width * 90 / 100, height=height * 7 / 100, x=width * 5 / 100, y=height * 0.5 / 100)

    #Add Line
    add_line_border(self.base_frame, self.color, self.height, self.width)

    def add_line_border(base_frame, color, height, width):
        line_canvas = Canvas(base_frame, bg=color, borderwidth=0, relief="flat", highlightthickness=0)
        line_canvas.place(width=width - 4, height=5, x=2, y=height * 10 / 100)
        line_canvas.create_line(0, 0, width, 0, fill="#787878")

     button_font = add_action_frame(self.base_frame, self.color, self.height, self.width)

    #Search history
    add_history_frame(self.base_frame, button_font, self.color, self.height, self.width)
    def add_history_frame(base_frame, button_font, color, height, width):
        sfw = width * 0.638
        sfh = height * 0.87
        label_frame_search = LabelFrame(base_frame, text="History", font=button_font, pady=sfw * 2 / 100,padx=sfw * 2 / 100, bg=color)
        label_frame_search.place(width=sfw, height=sfh, x=width * 0.36, y=height * 0.12)
        
    

So we are done with all frame and background UI. Now we will add all the entry box and submit button in action frame to add money.

    
    # Add Credit UI

    self.amount_entrylable = CustomEntrySimple(self.base_frame, 300, 60, ("Lucida Grande", AppConstant.FONT_SIZE - 6),
                                                   self.color, "Amount")
    self.amount_entrylable.place(x=50, y=150)

    self.des_label = Label(self.base_frame, text="Description", font=('Lucida Grande', AppConstant.FONT_SIZE - 6),
                               background=self.color, foreground="black", anchor=W)
    self.des_label.place(width=300, height=20, x=50, y=230)

    
    self.inputtxt = Text(self.base_frame, highlightthickness=2, bg="white", fg="black",
                             font=('Lucida Grande', AppConstant.FONT_SIZE - 6))
    self.inputtxt.place(x=50, y=260, height=200, width=300)


    self.show_credit_button()
        
    

Here is our class CustomEntrySimple:

    
    class CustomEntrySimple(tk.Canvas):

    def __init__(self, parent, width, height, font, color, text):
        tk.Canvas.__init__(self, parent, borderwidth=0, relief="flat", highlightthickness=0, bg=color)

        self.width = width
        self.height = height
        self.color = color

        self.create_text(6, 5, anchor=W, font=font, text=text, fill="#000000")
        self.create_line(5, height - 8, width - 5, height - 8, fill="#808080")

        frame = Frame(parent,width=width * 95 / 100, height=height * 50 / 100, bg=color)
        self.entry = Entry(frame, bg=color, bd=0, highlightthickness=0, font=font)

        self.entry.place(relwidth=1, relheight=1, x=0, y=0)

        self.create_window(6, height / 2 - (height * 50 / 100) / 2, anchor=NW, window=frame)
        self.update()

        (x0, y0, x1, y1) = self.bbox("all")
        width = (x1 - x0)
        height = (y1 - y0)
        self.configure(width=width, height=height)
        

Create a "Add Money" button and show it.

    
    def show_credit_button(self):
        self.add_button = RoundedButton(self.base_frame, 250, 130 / 2.56, self.color, "images/button33.png",
                                        "Add Money",font=("Lucida Grande", AppConstant.FONT_SIZE - 2),
                                        command=self.add_money_click)
        self.add_button.place(x=75, y=self.height * 0.85)
    
Here is our class RoundedButton,create class RoundedButton and put that code in seperate class "Util" because we are going to use it multiple time in our project.:

    
class RoundedButton(tk.Canvas):

    def __init__(self, parent, width, height, bg, icon_path, text, font, command=None):
        tk.Canvas.__init__(self, parent, borderwidth=0, relief="flat", highlightthickness=0, bg=bg)
        self.command = command
        self.width = width
        self.height = height
        self.text = text
        self.font = font

        original = Image.open(icon_path)
        resized = original.resize((int(width), int(height)), Image.ANTIALIAS)
        self.image = ImageTk.PhotoImage(resized)

        self.shape(width, height)
        (x0, y0, x1, y1) = self.bbox("all")
        width = (x1 - x0)
        height = (y1 - y0)
        self.configure(width=width, height=height)
        self.bind("", self._on_press)
        self.bind("", self._on_release)

    def shape(self, width, height):
        self.create_image(0, 0, image=self.image, anchor=NW)
        self.create_text(width / 2, height / 2, anchor=CENTER, font=self.font, text=self.text, fill="#FFFFFF")

    def shape_press(self, width, height):
        self.create_image(0, 0, image=self.image, anchor=NW)
        self.create_text(width / 2, height / 2, anchor=CENTER, font=self.font, text=self.text, fill="#000000")

    def _on_press(self, event):
        self.configure(relief="sunken")
        self.delete("all")
        # self.update()
        self.shape_press(self.width, self.height)

    def _on_release(self, event):
        self.configure(relief="raised")
        self.delete("all")
        self.shape(self.width, self.height)
        if self.command is not None:
        self.command()
        

Now Create a History UI for already added money history in expense sheet. First we create a lable for user name.

    
    self.label_name = Label(self.base_frame, font=("Lucida Grande", AppConstant.FONT_SIZE - 3), text="Name : " + AppConstant.USER_NAME,
                           anchor=CENTER,bg=self.color)
    self.label_name.place(x=self.width / 2 - 150, y=self.height * 0.20)
                        

Fetch data from database and show it in table form with the use of "Treeview" of Tkinter.

    
        conn = Util.connect_db()
        cursor = conn.cursor()
        status = "Credit"
       
        style = ttk.Style()
        
        style.layout("Custom.Treeview.Heading", [
            ("Custom.Treeheading.cell", {'sticky': 'nswe'}),
            ("Custom.Treeheading.border", {'sticky': 'nswe', 'children': [
                ("Custom.Treeheading.padding", {'sticky': 'nswe', 'children': [
                    ("Custom.Treeheading.image", {'side': 'right', 'sticky': ''}),
                    ("Custom.Treeheading.text", {'sticky': 'we'})
                ]})
            ]}),
        ])
        
        style.map("Custom.Treeview", background=[('selected', '#ad51ad')])
        style.configure("Custom.Treeview", highlightthickness=0, bd=0, font=('Calibri', 11), rowheight=30)

        self.table_heading()

        self.tree = ttk.Treeview(self.base_frame, height=13, show='tree', style="Custom.Treeview")
        self.tree.tag_configure('odd', background='#ffbfff', foreground="#000000", )
        self.tree.tag_configure('even', background='#FFFFFF', foreground="#000000", )
        self.tree.place(x=self.width / 2 - 150, y=230)
        self.tree["columns"] = "1", "2", "3", "4"
        self.tree.column("#1", width=170)
        self.tree.column("#0", width=0)
        self.tree.column("#2", width=170)
        self.tree.column("#3", width=170)
        self.tree.column("#4", width=200)


        self.update_table_data()


        vsb = ttk.Scrollbar(self.base_frame, orient="vertical", command=self.tree.yview)
        vsb.place(x=self.width - 24, y=230, height=395)

        self.tree.configure(yscrollcommand=vsb.set)
        self.tree.column("#1", anchor=tk.CENTER)
        self.tree.column("#2", anchor=tk.CENTER)
        self.tree.column("#3", anchor=tk.CENTER)
        self.tree.column("#4", anchor=tk.CENTER)



        self.tree.heading("#1", text="User Id", anchor=tk.CENTER)
        self.tree.heading("#2", text="Name")
        self.tree.heading("#3", text="Contact No")
        self.tree.heading("#4", text="Email Id")


        

        root.attributes('-alpha', 0.0)
        Util.center(root)
        root.attributes('-alpha', 1.0)

    
    

We have created our own heading for table, lets configure it.

    
def table_heading(self):

    heading_y = 200

    bg_color = "#800080"
    canvas = Canvas(self.base_frame, width=720, height=30)
    canvas.create_rectangle(0, 0, 720, 30, fill=bg_color)
    canvas.place(x=self.width / 2 - 153, y=heading_y - 3)



    staff_name_label = Label(self.base_frame, text="Credit",font=('Calibri', AppConstant.FONT_SIZE - 3, 
                                'bold'), background=bg_color,foreground="white")
    staff_name_label.place(x=self.width / 2 - 110, y=heading_y, width=120)
    staff_name_label.configure(anchor="center")

    staff_email_label = Label(self.base_frame, text="Credit Date",font=('Calibri', AppConstant.FONT_SIZE - 3, 
                                'bold'), background=bg_color,foreground="white")
    staff_email_label.place(x=self.width / 2 + 60, y=heading_y, width=130)
    staff_email_label.configure(anchor="center")

    staff_contact_label = Label(self.base_frame, text="Balance",font=('Calibri', AppConstant.FONT_SIZE - 3, 
                                'bold'), background=bg_color,foreground="white")
    staff_contact_label.place(x=self.width / 2 + 230, y=heading_y, width=120)
    staff_contact_label.configure(anchor="center")



    staff_adds_label = Label(self.base_frame, text="Description",font=('Calibri', AppConstant.FONT_SIZE - 3,
                                 'bold'), background=bg_color,foreground="white")
    staff_adds_label.place(x=self.width / 2 + 400, y=heading_y, width=140)
    staff_adds_label.configure(anchor="center")

        

UI part is completed, lets move to funtionality. First we need to add click on "Add Customer" button.

    
    def add_money_click(self):
        conn = Util.connect_db()
        cursor = conn.cursor()

        var = ""
        amount = ""
        decription = ""
        credit_date = datetime.today().strftime('%Y-%m-%d')
        debit_date = datetime.today().strftime('%Y-%m-%d')
        user_id = AppConstant.USER_ID
        balance = 0
        old_credit = 0
        old_debit = 0
        is_amount_entered = False
        is_descrip_entered = False

        if self.amount_entrylable.entry.get() == "" or self.amount_entrylable.entry.get() == " ":
            var += " Amount Should not be empty, "
        else:
            amount = self.amount_entrylable.entry.get()
            is_amount_entered = True

        if self.inputtxt.get(1.0, "end-1c") == "" or self.inputtxt.get(1.0, "end-1c") == " ":
            var += " Description Should not be empty, "
        else:
            decription = self.inputtxt.get(1.0, "end-1c")
            is_descrip_entered = True


        if is_amount_entered and is_descrip_entered:
            cursor.execute(
                'SELECT credit FROM statement where user_id IS ?', (user_id,))
            sql_output = cursor.fetchall()

            for data in sql_output:
                for items in data:
                    if items != "":
                        old_credit = old_credit + items

            cursor.execute(
                'SELECT debit FROM statement where user_id IS ?', (user_id,))
            sql_output = cursor.fetchall()

            for data in sql_output:
                for items in data:
                    if items != "":
                        old_debit = old_debit + items


            

            balance = (old_credit - old_debit) + int(amount)
        

            debit = ""
            debit_date = ""

            cursor.execute('INSERT INTO statement(user_id, credit, debit, balance, credit_date, debit_date, description) VALUES(?,?,?,?,?,?,?)',
                            (user_id, amount, debit, balance, credit_date, debit_date, decription))

            conn.commit()


            messagebox.showinfo("Success", "Success credited successfully, ")

            self.amount_entrylable.entry.delete(0, 'end')
            self.inputtxt.delete('1.0', END)
            self.tree.delete(*self.tree.get_children())
            self.update_table_data()

        else:
            print(var)
            messagebox.showerror("showerror", var)

            

When we click on "Add Money", data will be added to database, after that we need to update the data on UI.

    
    def update_table_data(self):
        conn = Util.connect_db()
        cursor = conn.cursor()
        cursor.execute('SELECT credit, credit_date, balance, description FROM statement where user_id IS ?', (AppConstant.USER_ID,))
        self.sql_output = cursor.fetchall()

        count = 0
        for data in self.sql_output:
            if count % 2 == 0:
                self.tree.insert('', 'end', values=data, tags=('even',))
            else:
                self.tree.insert('', 'end', values=data, tags=('odd',))
            count = count + 1
    

At last we will manage closing of window

    
    def on_closing():
                        
        root.destroy()
        args[0].deiconify()
                       
    root.protocol("WM_DELETE_WINDOW", on_closing)
                       

Programmer Mirta is for learning and training. Projects might be simple to improve learning. Projects are constantly reviewed to avoid errors, but we cannot assure full correctness of all content. While using Programmer Mitra, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 2021 by Programmer Mitra. All Rights Reserved.