Tkinter Module: Widgets & MySQL Integration
Tkinter Module: Widgets & MySQL Integration
Tkinter
Module:
Before we proceed, let's define some of the
common terms.
Window:
This term has different meanings in different
contexts, but in general it refers to a rectangular
area somewhere on your display screen.
Top-level window:
A window that exists independently on your
screen. It will be decorated with the standard
frame and controls for your system's desktop
manager. You can move it around on your
desktop. You can generally resize it, although your
application can prevent this.
4
Widget:
The generic term for any of the building blocks
that make up an application in a graphical user
interface. Examples of widgets: buttons, radio
buttons, text fields, frames, and text labels.
Frame:
In Tkinter, the Frame widget is the basic unit of
organization for complex layouts. A frame is a
rectangular area that can contain other widgets.
Child, parent:
When any widget is created, a parent child
relationship is created. For example, if you place a
text label inside a frame, the frame is the parent
of the label. There are two main methods which
the user need to remember while creating the
Python application with GUI.
5
1. Tk(): To create a main window, tkinter
offers a method ‘Tk()’. The basic code used to
create the main window of the application is:
from tkinter import *
master = Tk()
Then title, geometry, resizable properties of
the master window are set.
Resizable(width=value, height=value):If
width is true, allow horizontal resizing. If
height is true, allow vertical resizing.
7
the window is not closed. master.mainloop()
tkinter also offers access to the geometric
configuration of the widgets (e.g. label, entry,
button, list box, scrollbar, canvas, image etc.)
which can organize the widgets in the parent
windows. The following geometry manager
methods have been used:
Grid(row=value, column=value,
sticky=value)
method: Grid geometry manager places
the widgets in a 2-dimensional table, which
8
consists of a number of rows and columns.
The position of a widget is defined by a row
and a column number. Correspondingly,
widgets with the same row number but
different column numbers will be on the same
"line" and will be beside of each other, i.e. to
the left or the right. Sticky is a string that
defines how this element is to be positioned
within its parent. This string may contain zero
or more of the characters 'n', 's',
'e', and 'w'. For example, the value sticky='ns'
would stretch this element to adhere to the
north and south sides of the cavity within its
parent element. There are a number of
widgets which you can put in your tkinter
application. Some of the major widgets are
explained below:
9
updated any time as per the code. The general
syntax is: lbl=Label(master, text = value) where
master is the parameter used to represent the
parent window. The text parameter is set to
the text to be displayed in the label widget.
The configure method of
Label widget is used to set font, fg
(foreground color) of the text.
Button widget:
The Button widget is a standard Tkinter
widget, which is used for various kinds of
buttons. A button is a widget which is
designed for the user to interact with, i.e. if
the button is pressed by mouse click some
action might be started. They can also
contain text and images like labels. While
labels can display text in various fonts, a
button can only display text in a single font.
The text of a button can span more than one
10
line. A Python function or method can be
associated with a button. This function or
method will be executed, if the button is
pressed in some way. The general syntax is:
w=Button(master, text=value, width=value,
command=value) where master is the parent
window where the button widget is be placed,
text is button text, width is button width,
command is the function or method to be
called when the button is clicked. The configure
method of the button widget can be used set
value for font, fg (foreground colour of the
button text)
12
existing text and the constant END refers to
the position after the existing text.
13
.get()- Returns the current value of the
variable.
.set(value)- Changes the current value of the
variable.
mysql.connector Module:
MySQL Connector is a standardized database
driver provided by MySQL to access the MySQL
database from Python. In order to use this
module, the mysql connector is to be
downloaded and installed as follows:
C:\Users\Your
Name\AppData\Local\Programs\Python\Pyth
on36- 32\Scripts>python -m
pip install mysql-connector
import mysql.connector
15
If the above code is executed with no errors,
"MySQL Connector" is installed and ready to
be used.
Mysql.Connector.Error:
This module is the base class for all other
exceptions in the errors module. It can be used
to catch all errors in a single except statement.
The following example shows how we could
catch syntax errors:
cnx=mysql.connector.connect(user=’scott’,p
assword =’’tiger’,
database=’bookstore’)
cursor=cnx.cursor()
cursor.execute(“select * form book”)
# Syntax error in query cnx.close()
16
except mysql.connector.Error as err:
Mysql.connector.connect() :A
connection with the MySQL server can be
established using either the
mysql.connector.connect() function. The
syntax is as follows:
conn = mysql.connector.connect(host=value,
user=value, password=value, database=value)
17
Cursor() Function: A database cursor is a
useful control structure of database
connectivity. When you connect to a database
from within a program, the the sql query gets
sent to the database server, where it gets
executed and the result set (the set of records
retrieved as per query) is sent over the
connection to you in one go. But you may
want to access the retrieved data, one row at a
time. But query processing cannot happen as
one row at a time, so a special type of control
structure called database cursor can be
created that gets access of all the records as
per query (called the resultset) and allows you
to traverse the resultset row by row. The
syntax to create a database cursor is as
follows: cur
= conn.cursor()where we established
database connection through connection
object “conn” earlier and we have created a
18
cursor object “cur” using the same
connection object “conn”.
20
MAIN
CODE
import tkinter as tk
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root'
,passwd='tiger')
cursor=mydb.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS kartik")
cursor.execute("CREATE DATABASE IF NOT EXISTS bls")
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
username VARCHAR(255) UNIQUE,
password VARCHAR(255),
email VARCHAR(255)
)
""")
connection.commit()
finally:
if connection.is_connected():
22
cursor.close()
connection.close()
cursor.execute("""
CREATE TABLE IF NOT EXISTS idn (
itemnumber INT AUTO_INCREMENT PRIMARY KEY,
food VARCHAR(255),
cost VARCHAR(40)
23
)
""")
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('1','Tea','15'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('2','Espresso','15'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('3','Double Espresso','20'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('4','Latte','15'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('5','Americano','15'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('6','Strawberry Waffle','80'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('7','Cinnamon Roll','65'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('8','Croissant','45'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('9','Hot chocolate','40'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('10','Smoothie','30'))
24
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('11','Milkshake','20'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('12','Chocolate Waffle','80'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('13','Brownies','35'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('14','Cheesecake','45'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('15','Hazlenut Mocha','35'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('16','Java chip frappe','55'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('17','Tiramisu','80'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('18','Garlic Bread','60'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('19','French Toast','40'))
cursor.execute('insert ignore into idn
values(%s,%s,%s)',('20','Oats','40'))
connection.commit()
25
except mysql.connector.Error as error:
messagebox.showerror("Error", f"Failed to create idn
table: {error}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
26
cursor.execute("""
CREATE TABLE IF NOT EXISTS bills (
bill_id INT AUTO_INCREMENT PRIMARY KEY,
food VARCHAR(255),
cost DECIMAL(10, 2)
)
""")
connection.commit()
finally:
if connection.is_connected():
cursor.close()
connection.close()
27
create_users_table()
create_idn_table()
create_bills_table()
# NEW ACCOUNT
def open_create_account_window():
create_account_window = tk.Toplevel(root)
create_account_window.title("Create Account")
create_account_window.geometry('500x600+0+0')
create_account_window.config(bg="lightblue")
lbl_title=Label(create_account_window,text="CREATE
ACCOUNT",font=("times new
roman",40,"bold"),bg="black",fg='gold',bd=4,relief=RIDGE,jus
tify=CENTER)
lbl_title.place(x=0,y=0,width=500,height=80)
main_frme=Frame(create_account_window,bd=4,relief=RID
GE)
main_frme.place(x=50,y=100,width=400,height=450)
28
label_username = tk.Label(main_frme,
text="Username:",font=("times new
roman",12,"bold"),padx=10,pady=20)
label_username.grid(row=1, column=1,padx=10,pady=20)
entry_username =
tk.Entry(main_frme,width=29,font=("arial",10,"bold"))
entry_username.grid(row=1, column=2,pady=20)
label_password = tk.Label(main_frme,
text="Password:",font=("times new
roman",12,"bold"),padx=10,pady=20)
label_password.grid(row=2, column=1,padx=10,pady=20)
entry_password =
tk.Entry(main_frme,width=29,font=("arial",10,"bold"))
entry_password.grid(row=2, column=2,pady=20)
label_email = tk.Label(main_frme,
text="Email:",font=("times new
roman",12,"bold"),padx=10,pady=20)
label_email.grid(row=3, column=1,padx=10,pady=20)
29
entry_email =
tk.Entry(main_frme,width=29,font=("arial",10,"bold"))
entry_email.grid(row=3, column=2,pady=20)
def create_account():
new_username = entry_username.get()
new_password = entry_password.get()
new_email = entry_email.get()
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="tiger",
database="kartik"
)
cursor = connection.cursor()
if existing_user:
messagebox.showerror("Error", "Username already
exists. Please choose another one.")
else:
cursor.execute("INSERT INTO users (username,
password, email) VALUES (%s, %s, %s)",
(new_username, new_password, new_email))
connection.commit()
messagebox.showinfo("Success", "Account created
successfully!")
create_account_window.destroy()
finally:
if connection.is_connected():
31
cursor.close()
connection.close()
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="tiger",
database="kartik"
32
)
cursor = connection.cursor()
finally:
if connection.is_connected():
cursor.close()
33
connection.close()
# WELCOME WINDOW
def mp():
def fetch_bills():
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="tiger",
database="bls"
)
cursor = connection.cursor()
bill_details = []
34
for table in bill_tables:
table_name = table[0]
cursor.execute(f"SELECT food, cost FROM
{table_name}")
items = cursor.fetchall()
total_cost = sum(item[1] for item in items)
bill_details.append((table_name, items, total_cost))
connection.close()
return bill_details
def fetch_item(item_number):
try:
connection = mysql.connector.connect(
35
host="localhost",
user="root",
password="tiger",
database="kartik"
)
cursor = connection.cursor()
connection.close()
return item
36
def add_item_to_bill():
item_number = item_number_entry.get()
item_details = fetch_item(item_number) if
item_details:
food, cost = item_details
bill_listbox.insert(tk.END, f"{item_number}, {food}:
${cost}")
else:
messagebox.showerror("Error", f"Item with number
{item_number} not found in database.")
def make_bill():
bill_window = tk.Toplevel(mp)
bill_window.geometry('1200x600+0+0')
bill_window.title("Make Bill")
37
lbl_title=Label(bill_window,text="MAKE
BILL",font=("times new
roman",40,"bold"),bg="gold",fg="black",bd=4,relief=RIDGE,ju
stify=CENTER)
lbl_title.place(x=0,y=0,width=1200,height=100)
btn_frame=Frame(bill_window,bd=4,relief=RIDGE)
btn_frame.place(x=200,y=150,width=400,height=300)
def calculate_total_cost():
costFrame=Frame(bill_window,bd=4,relief=RIDGE,padx=2)
costFrame.place(x=200,y=450,width=400,height=100)
total_cost = sum(float(item.split('$')[1]) for item in
bill_listbox.get(0, tk.END))
cost_str='Total Cost: '+ str(total_cost)
#Total cost
totalcost_lbl=Label(costFrame,text="Total
Cost",font=("times new roman",12,"bold"),padx=2,pady=2)
totalcost_lbl.place(x=200,y=450,width=100,height=90)
38
lbl_total=Label(costFrame,text=cost_str,font=("arial",10,"bol
d"))
lbl_total.grid(row=3,column=1)
global item_number_entry
label_itemnumber = tk.Label(btn_frame, text="Enter
Item Number:",font=("times new
roman",12,"bold"),padx=10,pady=20)
label_itemnumber.grid(row=1,
column=1,padx=10,pady=20)
item_number_entry =
tk.Entry(btn_frame,width=29,font=("arial",10,"bold"))
item_number_entry.grid(row=1, column=2,pady=20)
39
finish_order_button = tk.Button(btn_frame, text="FINISH
ORDER",
command=calculate_total_cost,font=("arial",13,"bold"),fg="
black",width=12,bd=2)
finish_order_button.grid(row=3, column=1,
columnspan=2, padx=10, pady=10)
global menu_table
details_table1=Frame(bill_window,bd=2,relief=RIDGE)
details_table1.place(x=650,y=150,width=300,height=300)
scroll_x=ttk.Scrollbar(details_table1,orient=HORIZONTAL)
scroll_y=ttk.Scrollbar(details_table1,orient=VERTICAL)
menu_table=ttk.Treeview(details_table1,column=("Food",
"Cost", "Item
Number"),xscrollcommand=scroll_x.set,yscrollcommand=s
croll_y.set)
scroll_x.pack(side=BOTTOM,fill=X)
40
scroll_y.pack(side=RIGHT,fill=Y)
scroll_x.config(command=menu_table.xview)
scroll_y.config(command=menu_table.yview)
menu_table.heading("Food",text="Food Name")
menu_table.heading("Cost",text="Cost")
menu_table.heading("Item Number",text="Item
Number")
menu_table["show"]="headings"
menu_table.pack(fill=BOTH,expand=1)
menu_table.column("Food",width=70)
menu_table.column("Cost",width=70)
menu_table.column("Item Number",width=70)
menu_table.pack(fill=BOTH,expand=1)
41
global bill_listbox
bill_listbox = tk.Listbox(bill_window)
bill_listbox.place(x=40,y=150,width=100,height=200)
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="tiger",
database="kartik"
)
cursor = connection.cursor()
42
except mysql.connector.Error as error:
messagebox.showerror("Error", "Failed to connect to
MySQL database: {}".format(error))
finally:
if connection.is_connected():
cursor.close()
connection.close()
global total_cost
details_table=Frame(item_details_window,bd=2,relief=RIDG E)
43
details_table.place(x=50,y=50,width=800,height=380)
scroll_x=ttk.Scrollbar(details_table,orient=HORIZONTAL)
scroll_y=ttk.Scrollbar(details_table,orient=VERTICAL)
Cust_details_table=ttk.Treeview(details_table,column=("Foo d",
"Cost", "Item
Number"),xscrollcommand=scroll_x.set,yscrollcommand=s
croll_y.set)
scroll_x.pack(side=BOTTOM,fill=X)
scroll_y.pack(side=RIGHT,fill=Y)
scroll_x.config(command=Cust_details_table.xview)
scroll_y.config(command=Cust_details_table.yview)
Cust_details_table.heading("Food",text="Refer No")
Cust_details_table.heading("Cost",text="Cost")
Cust_details_table.heading("Item Number",text="Item
Number")
44
Cust_details_table["show"]="headings"
Cust_details_table.pack(fill=BOTH,expand=1)
Cust_details_table.column("Food",width=100)
Cust_details_table.column("Cost",width=100)
Cust_details_table.column("Item Number",width=100)
Cust_details_table.pack(fill=BOTH,expand=1)
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="tiger",
database="kartik"
)
cursor = connection.cursor()
45
cursor.execute("SELECT food, cost, itemnumber FROM
idn")
rows = cursor.fetchall()
for row in rows:
Cust_details_table.insert("", tk.END, values=row)
finally:
if connection.is_connected():
cursor.close()
connection.close()
Cust_details_table.pack()
def logout():
mp.destroy()
46
mp = tk.Tk()
mp.title("Restaurant Management system")
mp.geometry('1200x600+0+0')
lbl_title=Label(mp,text="RESTAURANT MANAGEMENT
SYSTEM",font=("times new
roman",40,"bold"),bg="gold",fg="black",bd=4,relief=RIDGE,ju
stify=CENTER)
lbl_title.place(x=0,y=0,width=1200,height=100)
button_frame=Frame(mp,bd=4,relief=RIDGE)
button_frame.place(x=0,y=150,width=250,height=400)
47
btn3 = tk.Button(button_frame,
text='LOGOUT',command=logout,font=("arial",13,"bold"),bg=
"black",fg="gold",width=15)
btn1.grid(row=1,column=1,padx=40,pady=20)
btn2.grid(row=2,column=1,padx=40,pady=20)
btn3.grid(row=3,column=1,padx=40,pady=20)
window_frame=Frame(mp,bd=4,relief=RIDGE)
window_frame.place(x=260,y=100,width=940,height=500)
mp.mainloop()
lbl_title=Label(root,text="RESTAURANT MANAGEMENT
SYSTEM",font=("times new
48
roman",40,"bold"),bg="gold",fg="black",bd=4,relief=RIDGE,ju
stify=CENTER)
lbl_title.place(x=0,y=0,width=1200,height=100)
btn_frame=Frame(root,bd=4,relief=RIDGE)
btn_frame.place(x=400,y=150,width=400,height=300)
label_username = tk.Label(btn_frame,
text="Username:",font=("times new
roman",12,"bold"),padx=10,pady=20)
label_username.grid(row=1, column=1,padx=10,pady=20)
entry_username =
tk.Entry(btn_frame,width=29,font=("arial",10,"bold"))
entry_username.grid(row=1, column=2,pady=20)
label_password = tk.Label(btn_frame,
text="Password:",font=("times new
roman",12,"bold"),padx=10,pady=20)
label_password.grid(row=2, column=1,padx=10,pady=20)
49
entry_password =
tk.Entry(btn_frame,width=29,font=("arial",10,"bold"),show='*
')
entry_password.grid(row=2, column=2,pady=20)
root.mainloop()
50
OUTPUT
51
2. Enter username password and email.
52
3. Click menu to view menu and make bill to choose
items for bill
preparation.
53
4. Add items according to the item numbers and
finish order to get the bill.
54
DATABASE
SCREENSHOTS
55
56
57
BIBLIOGRAPHY
•https://cbsepython.in/class11computer-science-
project-inpython/
• https:/ /w w w.programiz.com/py th on pr
ogramming/meth ods/
• https:/ /w w w.w3schools.com/py tho n
• https://www.scribd.com/document/530
393959/Class-12-ProjectRailwayReservation
• https:/ /w w w.ge eksforgeeks.org/py t honp r
ogramming - examples/
• https:/ /w w w.tu torial gatewa y.org/py t hon -
programmin g - examples/
https://www.w3schools.com/mysql/mys
ql_examples.asp
• https:/ /w w w.mysqltuto rial.org/
58
TEACHER’S REMARK
Remark:
Signature
59
60