Issue Book

Issue Book

Above UI we are going to create by Tkinter for issue book to the student in our Library 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.

    

        self.root = tk.Toplevel(self)
        self.root.title("Issue Book")

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

        # Get screen size
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.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)

            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(self.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 Name
    add_heading_label(self.base_frame, self.color, AppConstant.FONT_SIZE, self.height, self.width)

    def add_heading_label(base_frame, color, font_size, height, width):
        label_heading = Label(base_frame, text="Issue Book", anchor=CENTER, bg=color,
                            font=("Lucida Grande", font_size + 6))
        label_heading.place(width=width * 90 / 100, height=height * 5 / 100, x=width * 5 / 100, y=height * 0.2 / 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 * 7 / 100)
        line_canvas.create_line(0, 0, width, 0, fill="#787878")

    # Add Button Font
    button_font = add_action_frame(self.base_frame, self.color, self.height, self.width)

    def add_action_frame(base_frame, color, height, width):
        afw = width * 0.35
        afh = height * 0.91

        button_font = ("Lucida Grande", AppConstant.FONT_SIZE - 6)
        label_frame_action = LabelFrame(base_frame, text="Actions", font=button_font, pady=afw * 2 / 100,
                                    padx=afw * 2 / 100, bg=color)
        label_frame_action.place(width=afw, height=afh, x=width * 0.65, y=height * 0.09)
        return button_font

    add_book_search_frame(self.base_frame, button_font, self.color, self.height, self.width)

    def add_book_search_frame(base_frame, button_font, color, height, width):
        sfw = width * 0.638
        sfh = height * 0.45

        label_frame_search = LabelFrame(base_frame, text="Search Book", font=button_font, pady=sfw * 2 / 100,
                                    padx=sfw * 2 / 100, bg=color)
        label_frame_search.place(width=sfw, height=sfh, x=0, y=height * 0.09)

    add_student_search_frame(self.base_frame, button_font, self.color, self.height, self.width)

    def add_student_search_frame(base_frame, button_font, color, height, width):
        sfw = width * 0.638
        sfh = height * 0.45

        label_frame_search = LabelFrame(base_frame, text="Search Student", font=button_font, pady=sfw * 2 / 100,
                                    padx=sfw * 2 / 100, bg=color)
        label_frame_search.place(width=sfw, height=sfh, x=0, y=height * 0.55)



        
    

Now Create a Search UI for Search Book in database. First we create a entry box to search Book with Book Id and Book Name.

    
        self.search_book_var = CustomEntry(self.base_frame, 300, 55, 10, 2, self.color, "Search Book",
                                           "images/ic_search.png")
        self.search_book_var.place(x=25, y=95)
        self.search_book_var.entry.bind('', self.search_book)
        

Here's the logic to search Book in table

    
    def search_book(self, *arg):
        if self.search_book_var.entry.get() != "":
            self.tree.delete(*self.tree.get_children())
            conn = Util.connect_db()
            cursor = conn.cursor()
            cursor.execute(
                "SELECT book_number, book_name, book_authorname,book_cost, book_available_count FROM `book` WHERE `book_number` LIKE ? OR `book_name` LIKE ?",
                ('%' + str(self.search_book_var.entry.get()) + '%',
                 '%' + str(self.search_book_var.entry.get()) + '%'))
            sql_output = cursor.fetchall()
            count = 0
            for data in 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

        else:
            self.reset_book()

    def reset_book(self):
        self.tree.delete(*self.tree.get_children())
        self.get_book_data()                        
        

We have created a Database named "library.db", lets connect that database and put that code in seperate class "Util" because we are going to use it multiple time in our project.

    
    class Util:

        @staticmethod
        def connect_db():
            db = None
            try:
                db = sql.connect("library.db")
                return db
            except sql.Error as error:
                print("Failed to insert data into sqlite table", error)
                

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

    

    style = ttk.Style()
        #   style.element_create("Custom.Treeheading.border", "from", "default")
        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.configure("Custom.Treeview", highlightthickness=0, bd=0, font=('Calibri', 11), rowheight=30)

    self.book_table_heading()

    self.tree = ttk.Treeview(self.base_frame, height=4, columns=("c1", "c2", "c3", "c4", "c5"),
                                 selectmode="extended", show='tree', style="Custom.Treeview")
    self.tree.tag_configure('odd', background='#DFEBF6', foreground="#000000", )
    self.tree.tag_configure('even', background='#FFFFFF', foreground="#000000", )
    self.tree.place(x=20, y=195)
    self.tree.bind('<>', self.on_select_book)

    self.get_book_data()
    def get_book_data(self):
        db = Util.connect_db()
        cursor = db.cursor()

        cursor.execute(
            'SELECT book_number, book_name, book_authorname,book_cost, book_available_count FROM book WHERE book_available_count > 0')
        sql_output = cursor.fetchall()

    vsby = ttk.Scrollbar(self.base_frame, orient="vertical", command=self.tree.yview)
    vsby.place(x=self.width / 2 + 147, y=195, height=120)
    self.tree.configure(yscrollcommand=vsby.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.column("#5", anchor=tk.CENTER)
    self.tree.heading("#1", text="Book Number", anchor=tk.CENTER)
    self.tree.heading("#2", text="Book Name")
    self.tree.heading("#3", text="Book Author")
    self.tree.heading("#4", text="Available Copy")
    self.tree.heading("#5", text="Book Price")

    self.tree.column("#0", width=0)
    self.tree.column("#1", width=100)
    self.tree.column("#3", width=190)
    self.tree.column("#4", width=170)
    self.tree.column("#5", width=125)

    

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

    
    
    def book_table_heading(self):

        heading_y = 168
        bg_color = "#2929ff"
        text_color = "#ffffff"

        canvas = Canvas(self.base_frame, width=785, height=30)
        canvas.create_rectangle(0, 0, 1000, 30, fill=bg_color)
        canvas.place(x=20, y=heading_y - 3)
        book_id_label = Label(self.base_frame, text="Book Id", width=9,
                            font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
                            foreground=text_color)
        book_id_label.place(x=30, y=heading_y, width=120)
        book_id_label.configure(anchor="center")

        book_name_label = Label(self.base_frame, text="Name",
                            font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
                            foreground=text_color)
        book_name_label.place(x=180, y=heading_y, width=120)
        book_name_label.configure(anchor="center")

        book_authorname_label = Label(self.base_frame, text="Author",
                            font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
                            foreground=text_color)
        book_authorname_label.place(x=373, y=heading_y, width=120)
        book_authorname_label.configure(anchor="center")

        book_price = Label(self.base_frame, text="Price",
                            font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
                            foreground=text_color)
        book_price.place(x=556, y=heading_y, width=120)
        book_price.configure(anchor="center")

        book_total_count = Label(self.base_frame, text="Available",
                            font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
                            foreground=text_color)
        book_total_count.place(x=695, y=heading_y, width=100)
        book_total_count.configure(anchor="center")

        

Now Create a "ADD BOOK" Button for adding the book to the Selected book table.

    
    self.show_add_book_button()
    def show_add_book_button(self):
        self.add_button = RoundedButton(self.base_frame, 150, 130 / 3.75, self.color, "images/button3.png",
                                        "ADD BOOK",
                                        font=("Lucida Grande", AppConstant.FONT_SIZE - 2),
                                        command=self.on_add_book_click)
        self.add_button.place(x=320, y=self.height * 0.471)
        

Now Create a Search UI for Search Student in database. First we create a entry box to search Student with Student Id and Student Name.

    
        self.search_student_var = CustomEntry(self.base_frame, 300, 55, 10, 2, self.color, "Search Student",
                                              "images/ic_search.png")
        self.search_student_var.place(x=25, y=self.height * 0.60)
        self.search_student_var.entry.bind('', self.search_student)
        

Here's the logic to search data in table

    
    def search_student(self, *arg):
        if self.search_student_var.entry.get() != "":
            self.student_tree.delete(*self.student_tree.get_children())
            conn = Util.connect_db()
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM `student` WHERE `student_id` LIKE ? OR `name` LIKE ?",
                           ('%' + str(self.search_student_var.entry.get()) + '%',
                            '%' + str(self.search_student_var.entry.get()) + '%'))
            sql_output = cursor.fetchall()
            count = 0
            for data in sql_output:
                if count % 2 == 0:
                    self.student_tree.insert('', 'end', values=data, tags=('even',))
                else:
                    self.student_tree.insert('', 'end', values=data, tags=('odd',))
                count = count + 1

        else:
            self.reset_student()

    def reset_student(self):
        conn = Util.connect_db()
        cursor = conn.cursor()
        self.student_tree.delete(*self.tree.get_children())
        cursor.execute("SELECT * FROM `student` ORDER BY `student_id` ASC")
        sql_output = cursor.fetchall()
        count = 0
        for data in sql_output:
            if count % 2 == 0:
                self.student_tree.insert('', 'end', values=data, tags=('even',))
            else:
                self.student_tree.insert('', 'end', values=data, tags=('odd',))
            count = count + 1
        cursor.close()
        conn.close()                       
        

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

    

        self.student_table_heading()
        self.student_tree = ttk.Treeview(self.base_frame, height=4, columns=("c1", "c2", "c3", "c4"),
                                         show='tree', style="Custom.Treeview")
        self.student_tree.tag_configure('odd', background='#DFEBF6', foreground="#000000", )
        self.student_tree.tag_configure('even', background='#FFFFFF', foreground="#000000", )
        self.student_tree.place(x=20, y=self.height * 0.735)

        vsb = ttk.Scrollbar(self.base_frame, orient="vertical", command=self.student_tree.yview)
        vsb.place(x=self.width / 2 + 147, y=self.height * 0.735, height=120)
        self.student_tree.configure(yscrollcommand=vsb.set)

        self.student_tree.column("#0", width=0)
        self.student_tree.column("#1", width=100)
        self.student_tree.column("#2", width=280)
        self.student_tree.column("#1", anchor=tk.CENTER)
        self.student_tree.column("#2", anchor=tk.CENTER)
        self.student_tree.column("#3", anchor=tk.CENTER)
        self.student_tree.column("#4", anchor=tk.CENTER)

        self.get_student_data()
        def get_student_data(self):
            db = Util.connect_db()
            cursor = db.cursor()

            cursor.execute('SELECT * FROM student')
            sql_output = cursor.fetchall()

        self.student_tree.bind('<>', self.on_select_student)

    

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

    
    
    def student_table_heading(self):

        heading_y = self.height * 0.695
        bg_color = "#2929ff"
        text_color = "#ffffff"
        canvas = Canvas(self.base_frame, width=785, height=30)
        canvas.create_rectangle(0, 0, 1000, 30, fill=bg_color)
        canvas.place(x=20, y=heading_y - 3)

        student_id_label = Label(self.base_frame, text="Student Id",
                            font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
                            foreground=text_color)
        student_id_label.place(x=30, y=heading_y, width=120)
        student_id_label.configure(anchor="center")

        student_name_label = Label(self.base_frame, text="Name",
                            font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
                            foreground=text_color)
        student_name_label.place(x=222, y=heading_y, width=120)
        student_name_label.configure(anchor="center")

        student_contactno_label = Label(self.base_frame, text="Contact No",
                            font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
                            foreground=text_color)
        student_contactno_label.place(x=463, y=heading_y, width=120)
        student_contactno_label.configure(anchor="center")

        student_email = Label(self.base_frame, text="Email Id",
                            font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
                            foreground=text_color)
        student_email.place(x=650, y=heading_y, width=120)
        student_email.configure(anchor="center")

        

Now Create a "ADD STUDENT" Button for add the Student to the Issue to Label.

    
    self.show_add_student_button()
    def show_add_student_button(self):
        self.add_button = RoundedButton(self.base_frame, 170, 130 / 3.75, self.color, "images/button3.png",
                                        "ADD STUDENT",
                                        font=("Lucida Grande", AppConstant.FONT_SIZE - 2),
                                        command=self.add_student_button)
        self.add_button.place(x=310, y=self.height * 0.932)
        

Now Create a Table for selected book in the right side of the window and A Label for which student issued the book.

    
    self.selected_book_table_heading()

        selected_book_label = ttk.Label(self.base_frame, text="Selected Book:", width=15,
                                        font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background='white',
                                        foreground="black")
        selected_book_label.place(x=self.width / 2 + 210, y=110)

        self.selected_row = []
        self.book_list = []

        self.selected_book_tree = ttk.Treeview(self.base_frame, height=15, show="tree")
        self.selected_book_tree.place(x=self.width / 2 + 220, y=180)
        self.selected_book_tree["columns"] = "1", "2"
        self.selected_book_tree.column("#0", width=0)
        self.selected_book_tree.column("#1", width=100)
        self.selected_book_tree.column("#2", width=300)

        self.selected_book_tree.column("#1", anchor=tk.CENTER)
        self.selected_book_tree.column("#2", anchor=tk.CENTER)

        self.selected_book_tree.bind('<>', self.on_remove)

        selected_book_label = ttk.Label(self.base_frame, text="Issue To:", width=15,
                                        font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background='white',
                                        foreground="black")
        selected_book_label.place(x=self.width / 2 + 210, y=self.height * 0.78)


        

Now Create a "ISSUE BOOK" Button for Issuing the book to the student.

    
    self.submit_button = RoundedButton(self.base_frame, 200, 130 / 3.0, self.color, "images/button3.png",
                                           "ISSUE BOOK",
                                           font=("Lucida Grande", AppConstant.FONT_SIZE - 2),
                                           command=self.on_issue_book_click)
    self.submit_button.place(x=self.width * 0.75, y=self.height * 0.87)

    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()

        

Here the logic on Click "ISSUE BOOK" button

    

    def on_issue_book_click(self):
        self.insert_into_reader_table(self.selected_student_id, self.book_list)

    def insert_into_reader_table(self, student_id, book_number_list):
        db = Util.connect_db()
        cursor = db.cursor()

        s_no = None
        current_date = datetime.datetime.today().strftime('%Y-%m-%d')
        print(current_date)
        return_date = None
        fine_paid = None
        assigned_staff_id = AppConstant.STAFF_ID
        return_staff_id = ""

        for book_number in book_number_list:
            cursor.execute("INSERT INTO readers VALUES (?,?,?,?,?,?,?,?)", (
                s_no, student_id, book_number, current_date, return_date, fine_paid, assigned_staff_id, return_staff_id,
            ))

            cursor.execute("SELECT book_available_count FROM book WHERE book_number IS ?", (book_number,))
            rows = cursor.fetchone()
            print(rows[0])

            id_count = Util.convert_string_to_int(rows[0]) - 1

            cursor.execute("UPDATE book SET book_available_count = ? WHERE book_number = ?",
                           (id_count, book_number,))

        db.commit()

        messagebox.showinfo(title="Success", message="Book Issued")

        self.book_list.clear()
        self.selected_student_id = None
        self.selected_student_label.config(text="")
        self.tree.delete(*self.tree.get_children())
        self.get_book_data()
        self.selected_book_tree.delete(*self.selected_book_tree.get_children())

        

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.