Challenge

Project 1 - English Dictionary App & Library Book Management System

Question no 1 A : This project uses the skills learnt from week 1 to week 6. The aim of this project is to create an English Dictionary app that returns definitions of English words. When the application is started, it displays a menu as follows:

Main Menu

Add a new word Find the meaning Update a word Exit

Enter Choice:

If item 1 is selected, it should prompt for a word and then accept its meaning. This pair of word and its meaning should be stored in a file called ‘words.txt’. When item 2 is selected, it should prompt for a word, search that word in the file ‘words.txt’ and return the meaning if it is found. If the meaning is not found, it should display an appropriate message. Similarly, when choice 3 is entered, it should accept a word and update its meaning. In all the above three cases, the prompt should return to the main menu. The words and their meanings should be stored as a dictionary in words.txt, using the concept of serialization. If choice 4 is selected, a graceful exit should be performed.

In [ ]:
 
# I have used json module since it is stores the data in a dictionary format and it is easy to access the data 
# with json. So i have replaced "words.txt" to "words.json"
​
import json
​
def display_menu():
    
    print("\nMain Menu: ")
    
    print("\n1. Add a new word\n2. Find the meaning\n3. Update a word\n4. Exit")
    
    choice = input("\nEnter the choice: ")
​
    if(choice == '1' or choice == '2' or choice == '3' or choice == '4'):
        
        return choice
    
    else:
        
        print("Wrong choice!. Try again...")
        
        display_menu()
        
if __name__ == '__main__':
    
    dictionary = {}
    
    with open("words.json", 'w') as f:
        
        json.dump(dictionary, f)
    
    while(True):
        
        choice = display_menu()
        
        if(choice == '1'):
            
            word = input("\nPlease enter a word: ")
            
            meaning = input("Please enter the meaning: ")
        
            with open("words.json") as f:
                
                dictionary = json.load(f)
                
                dictionary[word] = meaning
                
                with open("words.json",'w') as f2:
                    
                    json.dump(dictionary, f2)
             
        elif(choice == '2'):
​
            word = input("\nPlease enter a word: ")
             
            with open("words.json") as f:
                
                dictionary = json.load(f)
                
                if(word in dictionary):
                    
                    print(f"\nThe meaning of {word} is: {dictionary[word]}")
                
                else:
                    
                    print("Word not found...")
            
        elif(choice == '3'):
            
            word = input("\nPlease enter a word: ")
            
            meaning = input("Please enter the updated meaning: ")
            
            with open("words.json") as f:
                
                dictionary = json.load(f)
                
                if(word not in dictionary):
                    
                    print("word not found! New word added to dictionary..")
                    
                dictionary[word] = meaning
                
                with open("words.json",'w') as f2:
                    
                    json.dump(dictionary, f2)
        
        elif(choice == '4'):
            
            print("\nThank you!\nExiting...")
            
            exit()
            
main()
OUTPUT :
Main Menu: 

1. Add a new word
2. Find the meaning
3. Update a word
4. Exit

Enter the choice: 1

Please enter a word: Pandemonium
Please enter the meaning: Uproar

Main Menu: 

1. Add a new word
2. Find the meaning
3. Update a word
4. Exit

Enter the choice: 2

Please enter a word: whistleblower
Word not found...

Main Menu: 

1. Add a new word
2. Find the meaning
3. Update a word
4. Exit

Enter the choice: 3

Please enter a word: pandemonium
Please enter the updated meaning: Great noise and confusion
word not found! New word added to dictionary..

Main Menu: 

1. Add a new word
2. Find the meaning
3. Update a word
4. Exit

Enter the choice: 4

Thank you!
Exiting...

Main Menu: 

1. Add a new word
2. Find the meaning
3. Update a word
4. Exit

Enter the choice: 5
Wrong choice!. Try again...

Main Menu: 

1. Add a new word
2. Find the meaning
3. Update a word
4. Exit

Question no 1B : In this project, a Library Book Management System will be implemented with the front end GUI developed using Tkinter and the backend database implemented in SQLite. It is a single window tkinter GUI application which will implement CRUD( create, read, update, delete) operations on a ‘books’ database, in SQLite. The window will contain text widgets to accept / display book title, author, year of publication, ISBN (optional) and a large text area/ list box to display the records which match the search criteria.

In [42]:
 
from tkinter import *
​
import tkinter as tk
​
import sqlite3
​
import tkinter.ttk as ttk
​
import tkinter.messagebox as tkMessageBox
​
root=Tk()
​
root.title('A simple CRUD application')
​
def database():
    
    global con,cursor
    
    con = sqlite3.connect('books.db')
    
    cursor = con.cursor()
    
    cursor.execute("CREATE TABLE IF NOT EXISTS librarytable(booktitle TEXT, author TEXT, year INTEGER, isbn INTEGER)")
    
def displaybook():
    
    tree.delete(*tree.get_children())
    
    database()
    
    cursor.execute("SELECT * FROM librarytable ORDER BY booktitle ASC")
    
    fetch=cursor.fetchall()
    
    count = 0
    
    for data in fetch:
        
        tree.insert('','end',values=(data[0],data[1],data[2],data[3]))
        
        cursor.close()
    
    con.close()
    
    tk.messagebox.showinfo("Successfully fetched data !")
    
def searchbook():
    
     title_bookname = ((bookname.get()).title())
    
     title_author = ((author.get()).title())
        
     title_yearofpublication = ((yearofpublication.get()).title())
    
     title_isbn = ((isbn.get()).title())
    
     tree.delete(*tree.get_children())
    
     database()
    
     cursor.execute("SELECT * FROM librarytable")
    
     fetch =cursor.fetchall()
    
     count = 0
    
     for data in fetch:
        
          if(title_bookname == data[0]) and (title_author == data[1]) and (str(title_yearofpublication == str(data[2]))) and (str(title_isbn == str(data[3]))):
            
            tree.insert('','end',values=(data[0],data[1],data[2],data[3]))
            
            count+=1 
            
          elif(title_bookname == data[0]):
            
            tree.insert('','end',values=(data[0],data[1],data[2],data[3]))
            
            count+=1
            
          elif(title_author == data[1]):
            
            tree.insert('','end',values=(data[0],data[1],data[2],data[3]))
            
            count+=1
            
          elif(title_yearofpublication == str(data[2])):
            
            tree.insert('','end',values=(data[0],data[1],data[2],data[3]))
            
            count+=1
            
          elif(str(title_isbn) == str(data[3])):
                                                                         
            tree.insert('','end',values=(data[0],data[1],data[2],data[3]))
                                                                         
            count+=1
            
            if(count==0):
                                                                         
                tk.messagebox.showinfo(text = "No such book like this in library")
                                                                          
            cursor.close()
                                                                         
            con.close()
                               
            bookname.set("")                          
                                                                         
            author.set("")
                                                                         
            yearofpublication.set("")
                                                                         
            isbn.set("")   
            
def addbook():
    
    database()
    
    title_bookname = ((bookname.get()).title())
    
    title_author = ((author.get()).title())
    
    title_yearofpublication = str(year.get())
    
    title_isbn =str (isbn.get())
    
    if ((title_bookname =='') or (title_author =='') or (title_yearofpublication =='') or (title_isbn) ==''):
        
        tk.messagebox.showinfo('Please fill all the details in the library')
        
    else:
        
        database()
        
        cursor.execute("INSERT INTO librarytable(bookname, author, yearofpublication, isbn) VALUES(?,?,?,?)",(title_bookname, title_author, title_yearofpublication, title_isbn))
        
        con.commit()
        
        bookname.set("")
        
        author.set("")
        
        yearofpublication.set("")
        
        isbn.set("")
        
        cursor.close()
        
        con.close()
        
        tk.messagebox.showinfo('Values inserted in the library')
        
def deletebook():
    
    title_bookname = ((bookname.get()).title())
    
    title_author = ((author.get()).title())
    
    title_yearofpublication = (yearofpublication.get().title())
    
    title_isbn = ((isbn.get()).title())
    
    tree.delete(*tree.get_children())
    
    database()
    
    cursorobj.execute("SELECT * FROM librarytable")
    
    fetch=cursor.fetchall()
    
    count=0
    
    for data in fetch:
            
        if ((title_bookname == data[0]) and (title_author == data[1]) and (str(title_yearofpublication) == str(data[2])) and (str(title_isbn) == str(data[3]))):
            
            tempb = ("'"+str(title_bookname)+"'")
            
            tempa = ("'"+str(title_author)+"'")
            
            tempp = ("'"+str(title_yearofpublication)+"'")
            
            tempi = ("'"+str(titleisbn)+"'")
            
            temp1 ="DELETE FROM librarytable WHERE bookname = "+tempb +"and author= "+tempa +"and yearofpublication = "+tempp +"and isbn= "+tempi
            
            cursor.execute(temp1)
            
            con.commit()
            
            count+=1
            
        if(count==0):
            
            tk.messagebox.showinfo('No data with this name in the library')
        
        else:
        
            tk.messagebox.showinfo('Book no longer available in the library')
        
    bookname.set("")
    
    author.set("")
    
    yearofpublication.set("")
    
    isbn.set("")
    
    con.commit()
    
    cursor.close()
    
    con.close()
    
def issuebook():
    
    title_bookname = ((bookname.get()).title())
    
    title_author = ((author.get()).title())
    
    title_yearofpublication = (yearofpublication.get().title())
    
    title_isbn = ((isbn.get()).title())
    
    tree.delete(*tree.get_children())
    
    database()
    
    cursor.execute("SELECT * FROM librarytable")
​
    fetch = cursor.fetchall()
    
    cursor.execute("DELETE FROM librarytable")
    
    count=0
    
    for data in fetch:
        
        if(title_bookname == data[0]) and (title_author == data[1]) and (titleyearofpublication == str(data[2])) and (titleisbn == str(data[3])):
            
            if(count==0):
                
                count+=1
                
                tk.messagebox.showinfo('Book issued from the library')
                
            else:
                
                cursor.execute("INSERT INTO librarytable(bookname, author, yearofpublication, isbn) VALUES(?,?,?,?)",(data[0],data[1],data[2],data[3]))
                
                con.commit()
                
        else:
            
            cursor.execute("INSERT INTO librarytable(bookname, author, yearofpublication, isbn) VALUES(?,?,?,?)",(data[0],data[1],data[2],data[3]))
            
            con.commit()
            
    if(count==0):
        
        tk.messagebox.showinfo('No book with this detail in library')
        
    bookname.set("")
    
    author.set("")
    
    yearofpublication.set("")
    
    isbn.set("")
    
    con.commit()
    
    cursor.close()
    
    con.close()
    
​
    
​
def Exit():
    
    result = tkMessageBox.askquestion('Do you want to exit from library?', icon='warning')
    
    if(result=='yes'):
        
        root.destroy()
        
    else:
        
        tk.messagebox.showinfo('You will now return to the application screen of the library')  
        
        
        
#=============================Frames==================================================================
​
TitleFrame=Frame(root,width=1000,padx=20,bd=20,relief=RIDGE,bg="#FFBB00")
​
TitleFrame.pack(side=TOP)
​
lblTitle=Label(TitleFrame,width=45,font=('Lucida Sans',40),text='Library Book Managment Application',padx=12, fg='#000')
​
lblTitle.grid()
​
​
​
LeftFrame=Frame(root,bd=20,width=350,height=520,padx=20,relief=RIDGE,bg='yellow')
​
LeftFrame.pack(side=LEFT)
​
ButtonFrame=Frame(LeftFrame,bd=20,padx=20,relief=RIDGE,bg="#FFBB00")
​
ButtonFrame.pack(side=BOTTOM)
​
Form=Frame(LeftFrame,bd=20,width=150,height=520,padx=20,bg="#FFBB00")
​
Form.pack()
​
RightFrame=Frame(root,bd=20,width=900,height=520,padx=20,relief=RIDGE,bg='red')
​
RightFrame.pack(side=RIGHT)
​
​
​
#===========================================Variables===========================================
​
​
bookname = StringVar()
​
author = StringVar()
​
yearofpublication = StringVar()
​
isbn = StringVar()
​
                                                                    
            
#===========================================Label&Entry===========================================
​
​
lbl_bookname = Label(Form,text="Author:",font=('Courier',18,'bold'), fg='#f00')
​
lbl_bookname.grid(row=1,column=0,sticky='w')
​
entry_bookname=Entry(Form,textvariable=author,width=35)
​
entry_bookname.grid(row=1,column=1)
​
lbl_authorname=Label(Form,text="Bookname:",font=('Courier',18,'bold'),fg='#f00')
​
lbl_authorname.grid(row=0,column=0,sticky='w')
​
entry_authorname=Entry(Form,textvariable=bookname,width=35)
​
entry_authorname.grid(row=0,column=1)
​
lbl_publishyear=Label(Form,text="Yearofpublication:",font=('Courier',18,'bold'),fg='#f00')
​
lbl_publishyear.grid(row=2,column=0,sticky='w')
​
entry_publishyear=Entry(Form,textvariable=yearofpublication,width=35)
​
entry_publishyear.grid(row=2,column=1)
​
lbl_ISBN=Label(Form,text="ISBN:",font=('Courier',18,'bold'), fg='#f00')
​
lbl_ISBN.grid(row=3,column=0,sticky='w')
​
entry_ISBN=Entry(Form,textvariable=isbn,width=35)
​
entry_ISBN.grid(row=3,column=1)
​
​
​
#===========================================Buttons===========================================
​
but_view=Button(ButtonFrame,text="Display",width=9,font=('Courier',18),command=displaybook,bg="#FFBB00", fg='#000')
​
but_view.grid(row=1,column=0)
​
but_search=Button(ButtonFrame,text="Search",width=9,font=('Courier',18),command=searchbook,bg="#FFBB00", fg='#000')
​
but_search.grid(row=1,column=1)
​
but_add=Button(ButtonFrame,text="Add",width=9,font=('Courier',18),command=addbook,bg="#FFBB00", fg='#000')
​
but_add.grid(row=1,column=2)
​
but_issue=Button(ButtonFrame,text="Issue",width=9,font=('Courier',18),command=issuebook,bg="#FFBB00", fg='#000')
​
but_issue.grid(row=1,column=3)
​
but_delete=Button(ButtonFrame,text="Delete",width=9,font=('Courier',18),command=deletebook,bg="#FFBB00", fg='#000')
​
but_delete.grid(row=1,column=4)
​
but_exit=Button(ButtonFrame,text="Exit",width=9,font=('Courier',18),command=Exit,bg="#FFBB00", fg='#000')
​
but_exit.grid(row=1,column=5)
​
​
​
#===========================================Scrollbar===========================================
​
scrollbary=Scrollbar(RightFrame)
​
scrollbarx=Scrollbar(RightFrame)
​
col=('Book_Name','Author_Name','Publication_year','ISBN')
​
tree=ttk.Treeview(RightFrame,columns=col,show='headings')
​
scrollbary=Scrollbar(RightFrame)
​
scrollbary.pack(side=RIGHT,fill=Y)
​
scrollbarx=Scrollbar(RightFrame)
​
scrollbarx.pack(side=BOTTOM,fill=X)
​
​
tree.heading("Book_Name",text="Bookname",anchor=W)
​
tree.heading("Author_Name",text="Author",anchor=W)
​
tree.heading("Publication_year",text="Yearofpublication",anchor=W)
​
tree.heading("ISBN",text="ISBN",anchor=W)
​
tree.column("Book_Name",minwidth=0,width=250)
​
tree.column("Author_Name",minwidth=0,width=250)
​
tree.column("Publication_year",minwidth=0,width=300)
​
tree.column("ISBN",minwidth=0,width=250)
​
tree.pack(side=TOP,fill=BOTH)
​
root.configure(bg="#FFBB00")
​
root.mainloop()
    
​
Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.