-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryGUI.py
More file actions
550 lines (453 loc) · 25.3 KB
/
LibraryGUI.py
File metadata and controls
550 lines (453 loc) · 25.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import functools
import tkinter as tk
from tkinter import messagebox, ttk
from Library import Library
from Book import BookFactory
from Book import genre_types
from PIL import Image, ImageTk
class LibraryGUI:
"""Library system GUI class"""
def __init__(self, root):
"""Initialize the GUI components and show the main screen"""
self.root = root
self.root.title("Library System")
self.root.geometry("800x850") # Larger window size
# Creating Canvas for the background
self.canvas = tk.Canvas(self.root, width=800, height=800)
self.canvas.pack(fill="both", expand=True)
# Loading background image
self.background_image = self.load_transparent_image("backgroundbook.jpg", alpha=0.5)
self.background_label = self.canvas.create_image(0, 0, anchor="nw", image=self.background_image)
# Content frame
self.main_frame = tk.Frame(self.canvas, bg="#ffffff") # Frame with white background
self.main_frame.pack(padx=20, pady=20)
self.canvas.create_window(400, 400, window=self.main_frame, anchor="center") # Positioning the frame on the Canvas
# Creating an object of the Library system
self.library = Library()
# Displaying the main screen with options to login or register
self.show_main_screen()
self.book_factory = BookFactory()
self.root.protocol("WM_DELETE_WINDOW", self.logout_and_close)
def logout_and_close(self):
"""Log out and close the application"""
if self.library.logged_in_user == "librarian":
self.library.logout() # Logout function
self.root.quit() # End the GUI events
def load_transparent_image(self, filepath, alpha=0.5):
"""Load and apply transparency to the image"""
image = Image.open(filepath).convert("RGBA") # Loading image in RGBA format
alpha_layer = image.split()[3] # Alpha layer of the image
alpha_layer = alpha_layer.point(lambda p: int(p * alpha)) # Setting transparency
image.putalpha(alpha_layer) # Applying alpha layer to the image
return ImageTk.PhotoImage(image)
def show_main_screen(self):
"""Main screen to choose login or register"""
for widget in self.main_frame.winfo_children():
widget.destroy()
self.title_label = tk.Label(self.main_frame, text="Welcome to the Library System", font=("Arial", 24)) # Larger text size
self.title_label.grid(row=0, column=0, columnspan=2, pady=40)
self.login_button = tk.Button(self.main_frame, text="Login", width=30, height=2, font=("Arial", 14), command=self.show_login_screen) # Larger button size
self.login_button.grid(row=1, column=0, pady=20)
self.register_button = tk.Button(self.main_frame, text="Register", width=30, height=2, font=("Arial", 14), command=self.show_registration_screen) # Larger button size
self.register_button.grid(row=2, column=0, pady=20)
def show_login_screen(self):
"""Login screen"""
for widget in self.main_frame.winfo_children():
widget.destroy()
self.username_label = tk.Label(self.main_frame, text="Username:", font=("Arial", 14))
self.username_label.grid(row=0, column=0, pady=20)
self.username_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.username_entry.grid(row=0, column=1, pady=20)
self.password_label = tk.Label(self.main_frame, text="Password:", font=("Arial", 14))
self.password_label.grid(row=1, column=0, pady=20)
self.password_entry = tk.Entry(self.main_frame, show="*", font=("Arial", 14))
self.password_entry.grid(row=1, column=1, pady=20)
self.login_button = tk.Button(self.main_frame, text="Login", width=20, height=2, font=("Arial", 14), command=self.login)
self.login_button.grid(row=2, column=0, columnspan=2, pady=20)
self.back_button = tk.Button(self.main_frame, text="Back", width=20, height=2, font=("Arial", 14),bg="lightblue", command=self.show_main_screen)
self.back_button.grid(row=3, column=0, columnspan=2, pady=20)
def show_registration_screen(self):
"""Registration screen"""
for widget in self.main_frame.winfo_children():
widget.destroy()
self.username_label = tk.Label(self.main_frame, text="Username:", font=("Arial", 14))
self.username_label.grid(row=0, column=0, pady=20)
self.username_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.username_entry.grid(row=0, column=1, pady=20)
self.password_label = tk.Label(self.main_frame, text="Password:", font=("Arial", 14))
self.password_label.grid(row=1, column=0, pady=20)
self.password_entry = tk.Entry(self.main_frame, show="*", font=("Arial", 14))
self.password_entry.grid(row=1, column=1, pady=20)
self.register_button = tk.Button(self.main_frame, text="Register", width=30, height=2, font=("Arial", 14), command=self.register_user)
self.register_button.grid(row=2, column=0, columnspan=2, pady=20)
self.back_button = tk.Button(self.main_frame, text="Back", width=20, height=2, font=("Arial", 14) ,bg="lightblue", command=self.show_main_screen)
self.back_button.grid(row=3, column=0, columnspan=2, pady=20, )
def register_user(self):
"""Register librarian"""
username = self.username_entry.get()
password = self.password_entry.get()
try:
result = self.library.register_user(username, password)
messagebox.showinfo("Registration", result)
self.show_main_screen()
except ValueError as e:
messagebox.showinfo("Registration", e)
def login(self):
"""Login function"""
username = self.username_entry.get()
password = self.password_entry.get()
try:
result = self.library.login(username, password)
if result == "librarian":
self.show_librarian_options()
else:
messagebox.showerror("Login Error", result)
except ValueError as e:
messagebox.showinfo("Login", e)
def show_librarian_options(self):
"""Librarian options screen"""
for widget in self.main_frame.winfo_children():
widget.destroy()
# Stretching rows and columns
self.main_frame.grid_rowconfigure(0, weight=1)
for i in range(1, 8): # Including buttons
self.main_frame.grid_rowconfigure(i, weight=1)
self.main_frame.grid_columnconfigure(0, weight=1)
# Title label
self.librarian_label = tk.Label(self.main_frame, text="Welcome librarian", font=("Arial", 24))
self.librarian_label.grid(row=0, column=0, pady=20, sticky="nsew") # Adjust size
# Buttons
buttons = [
("Add Book", self.add_book),
("Remove/Lend/Return/Search", self.options),
("View Books", self.display_options),
("LogOut", self.log_out),
]
for i, (text, command) in enumerate(buttons, start=1):
button = tk.Button(self.main_frame, text=text, font=("Arial", 14), command=command)
button.grid(row=i, column=0, pady=10, sticky="nsew") # Adjust size with "nsew"
# Add stretching to buttons to fill space
for i in range(len(buttons) + 1):
self.main_frame.grid_rowconfigure(i, weight=1)
self.main_frame.grid_columnconfigure(0, weight=1)
def log_out(self):
"""Log out and return to the main screen"""
self.library.logout()
self.show_main_screen()
def add_book(self):
"""Add a new book to the library"""
# Clears all existing widgets from the screen
for widget in self.main_frame.winfo_children():
widget.destroy()
# Label and input field for the book title
self.title1_label = tk.Label(self.main_frame, text="Title:", font=("Arial", 14))
self.title1_label.grid(row=0, column=0, pady=20)
self.title1_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.title1_entry.grid(row=0, column=1, pady=20)
# Label and input field for the author name
self.author1_label = tk.Label(self.main_frame, text="Author:", font=("Arial", 14))
self.author1_label.grid(row=1, column=0, pady=20)
self.author1_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.author1_entry.grid(row=1, column=1, pady=20)
# Label and input field for the book genre
self.genre1_label = tk.Label(self.main_frame, text="Genre:", font=("Arial", 14))
self.genre1_label.grid(row=2, column=0, pady=20)
self.genre1_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.genre1_entry.grid(row=2, column=1, pady=20)
# Label and input field for the book year
self.year1_label = tk.Label(self.main_frame, text="Year:", font=("Arial", 14))
self.year1_label.grid(row=3, column=0, pady=20)
self.year1_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.year1_entry.grid(row=3, column=1, pady=20)
# Label and input field for the number of copies of the book
self.copies_label = tk.Label(self.main_frame, text="Copies:", font=("Arial", 14))
self.copies_label.grid(row=4, column=0, pady=20)
self.copies_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.copies_entry.grid(row=4, column=1, pady=20)
# Button to perform the book adding action
self.add_the_book_button = tk.Button(self.main_frame, text="Add Book", font=("Arial", 14),
command=self.handle_add_book)
self.add_the_book_button.grid(row=5, column=0, pady=20)
# Button to go back to the librarian options screen
self.back_button = tk.Button(self.main_frame, text="Back", font=("Arial", 14), bg="lightblue",
command=self.show_librarian_options)
self.back_button.grid(row=6, column=0, pady=20)
def handle_add_book(self):
"""Handle the action of adding a book"""
try:
# Attempt to add the book
result_message = self.library.add_book(self.title1_entry.get(), self.author1_entry.get(),
self.genre1_entry.get(), self.year1_entry.get(),
self.copies_entry.get())
except ValueError as e:
# Handle errors (e.g., unsupported genre or missing values)
result_message = f"Error: {str(e)}"
# Display the result message
self.show_result_message(result_message)
def show_result_message(self, message):
"""Display a result message to the user"""
# If there is a previous message, delete it
if hasattr(self, 'result_label'):
self.result_label.destroy()
# Show a new message to the user
self.result_label = tk.Label(
self.main_frame,
text=message,
font=("Arial", 12),
fg="green" if "added" in message else "green"
)
self.result_label.grid(row=6, column=0, columnspan=2, pady=20)
def options(self):
"""Remove a book"""
# Clear all widgets from the screen
for widget in self.main_frame.winfo_children():
widget.destroy()
# Label title
self.librarian_label = tk.Label(self.main_frame, text="Choose book from the list, for filters enter parameters:", font=("Arial", 14))
self.librarian_label.grid(row=0, column=0, columnspan=3, pady=20, sticky="nsew")
# Input fields for each parameter
self.title_label = tk.Label(self.main_frame, text="Title:", font=("Arial", 14))
self.title_label.grid(row=1, column=0, pady=10, sticky="e")
self.title_entry = tk.Entry(self.main_frame, font=("Arial", 14), width=40) # Increased field width
self.title_entry.grid(row=1, column=1, pady=10, padx=10)
self.author_label = tk.Label(self.main_frame, text="Author:", font=("Arial", 14))
self.author_label.grid(row=2, column=0, pady=10, sticky="e")
self.author_entry = tk.Entry(self.main_frame, font=("Arial", 14), width=40) # Increased field width
self.author_entry.grid(row=2, column=1, pady=10, padx=10)
self.year_label = tk.Label(self.main_frame, text="Year:", font=("Arial", 14))
self.year_label.grid(row=3, column=0, pady=10, sticky="e")
self.year_entry = tk.Entry(self.main_frame, font=("Arial", 14), width=40) # Increased field width
self.year_entry.grid(row=3, column=1, pady=10, padx=10)
self.genre_label = tk.Label(self.main_frame, text="Genre:", font=("Arial", 14))
self.genre_label.grid(row=4, column=0, pady=10, sticky="e")
self.genre_entry = tk.Entry(self.main_frame, font=("Arial", 14), width=40) # Increased field width
self.genre_entry.grid(row=4, column=1, pady=10, padx=10)
# Search button
self.search_button = tk.Button(self.main_frame, text="Search Book", font=("Arial", 14),
command=self.update_search_results)
self.search_button.grid(row=5, column=0, columnspan=3, pady=20)
# List of books
self.books_listbox = tk.Listbox(self.main_frame, width=60, height=10, font=("Arial", 12))
self.books_listbox.grid(row=6, column=0, columnspan=3, pady=20)
# Additional buttons - split into 2 columns
self.Lend_button = tk.Button(self.main_frame, text="Lend Book", font=("Arial", 14),
command=lambda: self.handle_selected_book("lend"))
self.Lend_button.grid(row=7, column=0, pady=5)
self.Return_button = tk.Button(self.main_frame, text="Return Book", font=("Arial", 14),
command=lambda: self.handle_selected_book("return"))
self.Return_button.grid(row=7, column=1, pady=5)
self.Remove_button = tk.Button(self.main_frame, text="Remove Book", font=("Arial", 14),
command=lambda: self.handle_selected_book("remove"))
self.Remove_button.grid(row=8, column=0, pady=5)
self.Waiting_button = tk.Button(self.main_frame, text="Enter Waiting List", font=("Arial", 14),
command=lambda: self.handle_selected_book("waiting_list"))
self.Waiting_button.grid(row=8, column=1, pady=5)
# Back button
self.back_button = tk.Button(self.main_frame, text="Back", font=("Arial", 14), bg="lightblue",
command=self.show_librarian_options)
self.back_button.grid(row=9, column=0, columnspan=3, pady=20)
def handle_selected_book(self, function):
"""Handle the action for the selected book"""
selected_item = self.books_listbox.curselection() # Selects the chosen row
if selected_item:
# Get the selected book's title
selected_book = self.books_listbox.get(selected_item)
title = selected_book.split(" | ")[0].split(": ")[1] # Splitting the book title
# We can also extract other parameters like author, genre, and year
author = selected_book.split(" | ")[1].split(": ")[1]
genre = selected_book.split(" | ")[2].split(": ")[1]
year = int(selected_book.split(" | ")[3].split(": ")[1])
try:
# Create the book object
book = self.book_factory.create_book(title, author, genre, year)
# Using the switch-case structure
match function:
case "lend":
self.library.lend_book(book)
self.show_result_message(f"Book '{title}' lent successfully.")
case "return":
self.library.return_book(book)
self.show_result_message(f"Book '{title}' returned successfully.")
case "remove":
self.library.remove_book(book)
self.show_result_message(f"Book '{title}' removed successfully.")
case "waiting_list":
self.enter_waiting_list(book)
case _:
self.show_result_message("Invalid action")
except ValueError as e:
# Handle errors (e.g., unsupported genre or missing values)
self.show_result_message(f"Error: {str(e)}")
else:
self.show_result_message("Please select a book to operate on.")
def enter_waiting_list(self, book):
"""
Clears the current screen, displays input fields for name, phone number, and email address,
and provides buttons to either add the user to the waiting list for a specific book or go back
to the librarian options screen.
"""
for widget in self.main_frame.winfo_children():
widget.destroy()
self.name_label = tk.Label(self.main_frame, text="Name:", font=("Arial", 14))
self.name_label.grid(row=0, column=0, pady=20)
self.name_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.name_entry.grid(row=0, column=1, pady=20)
self.tel_label = tk.Label(self.main_frame, text="Phone (10 digits):", font=("Arial", 14))
self.tel_label.grid(row=1, column=0, pady=20)
self.tel_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.tel_entry.grid(row=1, column=1, pady=20)
self.email_label = tk.Label(self.main_frame, text="Email (<name>@gmail.com):", font=("Arial", 14))
self.email_label.grid(row=2, column=0, pady=20)
self.email_entry = tk.Entry(self.main_frame, font=("Arial", 14))
self.email_entry.grid(row=2, column=1, pady=20)
self.wait_book_button = tk.Button(self.main_frame, text=f"Enter waiting list for {book.title}",
font=("Arial", 14),
command=lambda: self.handle_waiting_book(book))
self.wait_book_button.grid(row=3, column=0, pady=20)
self.back_button = tk.Button(self.main_frame, text="Back", font=("Arial", 14), bg="lightblue",
command=self.show_librarian_options)
self.back_button.grid(row=4, column=0, pady=20)
def handle_waiting_book(self, book):
"""
Handles the action of adding a user to the waiting list for a specified book.
If the provided input is valid, the user is added to the waiting list, and a success message is displayed.
If there is an error (e.g., invalid input), an error message is shown.
"""
try:
self.library.enter_waiting_list(self.name_entry.get(), self.tel_entry.get(), self.email_entry.get(),
book)
self.show_result_message(f"You have successfully entered '{book.title}' waiting list.")
except ValueError as e:
self.show_result_message(f"Error: {str(e)}")
def update_search_results(self):
"""
Updates the search results displayed on the screen based on the user's search criteria (title, author, genre, year).
If no books are found, an error message is displayed. Otherwise, the books are listed in the books_listbox.
"""
try:
search_results = self.library.only_search(title=self.title_entry.get(), author=self.author_entry.get(),
genre=self.genre_entry.get(), year=self.year_entry.get())
except ValueError as e:
self.show_result_message(f"Error: {str(e)}")
self.books_listbox.delete(0, tk.END) # Clears the previous list
for _, row in search_results.iterrows():
display_text = f"Title: {row['title']} | Author: {row['author']} | Genre: {row['genre']} | Year: {row['year']}"
self.books_listbox.insert(tk.END, display_text)
def display_options(self):
"""
Displays options for the librarian to perform various tasks such as viewing all books, viewing available books,
viewing loaned books, and viewing popular books. It also allows the librarian to go back to the librarian options screen.
"""
for widget in self.main_frame.winfo_children():
widget.destroy()
self.main_frame.grid_rowconfigure(0, weight=1)
for i in range(1, 8): # Includes buttons
self.main_frame.grid_rowconfigure(i, weight=1)
self.main_frame.grid_columnconfigure(0, weight=1)
self.librarian_label = tk.Label(self.main_frame, text="Welcome librarian", font=("Arial", 24))
self.librarian_label.grid(row=0, column=0, pady=20, sticky="nsew")
buttons = [
("View all Books", functools.partial(self.display_books, "all")),
("View available Books", functools.partial(self.display_books, "available")),
("View loaned Books", functools.partial(self.display_books, "loaned")),
("Popular Books", functools.partial(self.display_books, "popularity")),
("View Books by category", functools.partial(self.display_books_by_category)),
("Back", self.show_librarian_options)
]
for i, (text, command) in enumerate(buttons, start=1):
button = tk.Button(self.main_frame, text=text, font=("Arial", 14), command=command)
button.grid(row=i, column=0, pady=10, sticky="nsew")
for i in range(len(buttons) + 1):
self.main_frame.grid_rowconfigure(i, weight=1)
self.main_frame.grid_columnconfigure(0, weight=1)
def display_books_by_category(self):
"""
Displays a screen that allows the librarian to select a book category. Once a category is selected, the librarian can
display books from that category.
"""
for widget in self.main_frame.winfo_children():
widget.destroy()
self.librarian_label = tk.Label(self.main_frame, text="Select a Book Category", font=("Arial", 24))
self.librarian_label.grid(row=0, column=0, columnspan=2, pady=20)
categories = [genre.value for genre in genre_types]
self.category_var = tk.StringVar()
self.category_dropdown = ttk.Combobox(
self.main_frame,
textvariable=self.category_var,
values=categories,
font=("Arial", 14),
state="readonly",
width=30
)
self.category_dropdown.grid(row=1, column=0, columnspan=2, pady=20, padx=20)
self.category_dropdown.set("Select a category") # Default text
self.display_button = tk.Button(
self.main_frame,
text="Display Books",
font=("Arial", 14),
command=self.handle_category_display,
width=20
)
self.display_button.grid(row=2, column=0, columnspan=2, pady=20)
self.back_button = tk.Button(
self.main_frame,
text="Back",
font=("Arial", 14), bg="lightblue",
command=self.display_options,
width=20
)
self.back_button.grid(row=3, column=0, columnspan=2, pady=20)
def handle_category_display(self):
"""
Handles the display of books based on the selected category.
If no category is selected, an error message is shown. If books are found, they are displayed.
"""
selected_category = self.category_var.get()
if selected_category == "Select a category":
messagebox.showerror("Error", "Please select a category")
return
try:
self.display_books(selected_category)
except ValueError as e:
messagebox.showerror("Error", str(e))
def display_books(self, option):
"""
Displays books based on the specified option. The options include viewing all books,
available books, loaned books, popular books, or books by category.
If no books are found, an error message is displayed.
"""
match option:
case "all":
books = self.library.display_all_books()
case "available":
books = self.library.display_available_books()
case "loaned":
books = self.library.display_loaned_books()
case "popularity":
books = self.library.display_10_popularity_books()
case _:
books = self.library.display_books_by_category(option)
if books.empty:
tk.messagebox.showinfo("Books", "No books available.")
raise ValueError("No books that match the display option.")
window = tk.Toplevel()
window.title("All Books")
window.geometry("1500x600")
frame = tk.Frame(window)
frame.pack(fill="both", expand=True)
tree = ttk.Treeview(frame, columns=list(books.columns), show="headings", height=20)
for column in books.columns:
tree.heading(column, text=column, anchor="center")
tree.column(column, anchor="center", width=150)
for _, row in books.iterrows():
tree.insert("", "end", values=list(row))
tree.pack(side="left", fill="both", expand=True)
scrollbar = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
tree.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right", fill="y")
window.mainloop()
# Run the GUI
if __name__ == "__main__":
root = tk.Tk()
app = LibraryGUI(root)
root.mainloop()