1. Description
- Python Tkinter multiple windows
- Python Tkinter user registration with multiple windows
- Python Tkinter multi-page access verification
Table of Contents
2. Multi-window problem
First, we will learn how to create multiple windows using Python Tkinter .
We're learning how multiple windows work. By multiple windows we mean connecting one page with other pages that are linked to each other and open in new tabs or even redirect us to new pages.
code :
import tkinter as tk
def New_Window():
Window = tk.Toplevel()
canvas = tk.Canvas(Window, height=HEIGHT, width=WIDTH)
canvas.pack()
HEIGHT = 300
WIDTH = 500
ws = tk.Tk()
ws.title("Python Guides")
canvas = tk.Canvas(ws, height=HEIGHT, width=WIDTH)
canvas.pack()
button = tk.Button(ws, text="Click ME", bg='White', fg='Black',
command=lambda: New_Window())
button.pack()
ws.mainloop()
Here are some key highlights of the given code.
- WS for the root window
- height = the height of the canvas widget.
- width = Width for canvas widget.
- BG is used for the background color.
- FG is used for the foreground color.
- Tut tut . Button() is used to add a button.
output:
In the above code, we made a simple button at the bottom of the screen. By clicking the button, a new window will open.
output:
As we can see in the output above, clicking the " Click Me " button will open a new window. The result is shown below.
final output
3. Python Tkinter user registration using multiple windows
In the next section, we'll look at a Python Tkinter user registered with multiple windows.
We have to make a registry where we have made block columns that contain information related to name, email, password. It also uses OTP verification emails to check if real users have a healthy database.
code:
Some of the libraries we use in this code are smtplib , sqlite3 and messagebox , random , EmailMessage , Tkinter and the email.message library. There are also some labels, fields, entries and buttons used here.
- sqllite3.connect() for database connection
- Label() is used to display text in this user just view not interactive.
- Entry() is a single line textbox that accepts a value from the user.
from tkinter import *
import re
from tkinter import messagebox
import sqlite3
import random
from email.message import EmailMessage
import smtplib
<strong># Database</strong>
try:
con = sqlite3.connect('website.db')
con.execute('''create table if not exists users(
fname text not null,
lname text not null,
email text not null,
password text not null);
''')
con.close()
except Exception as ep:
messagebox.showerror('', ep)
ws = Tk()
ws.title('Python Guides')
ws.geometry('500x400')
ws.config(bg="#447c84")
ws.attributes('-fullscreen',True)
<strong># functions</strong>
def otp_gen():
pass
cpy = ''
def sendOtp():
otp_no = ''
for _ in range(4):
r = random.randint(0, 9)
otp_no += str(r)
global cpy
cpy += otp_no
sender = "[email protected]"
reciever = em.get()
password = "Cute...pie@0823"
msg_body = f'otp is {cpy}'
msg = EmailMessage()
msg['subject'] = 'OTP'
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(sender,password)
smtp.send_message(msg)
print(cpy)
return cpy
def clr():
fname.delete(0, END)
lname.delete(0, END)
em.delete(0, END)
pwd.delete(0, END)
def submit():
enteredOtp = otp.get()
expectedOtp = cpy
print(expectedOtp)
fname_check = fname.get()
lname_check = lname.get()
em_check = em.get()
pwd_check = pwd.get()
otp_check = otp.get()
check_count = 0
if fname_check == "":
warn = "First name can't be empty!"
else:
check_count += 1
if lname_check == "":
warn = "Last name can't be empty!"
else:
check_count += 1
if em_check == "":
warn = "Email can't be empty!"
else:
check_count += 1
if pwd_check == "":
warn = "Password can't be empty!"
else:
check_count += 1
if otp_check == "":
warn = "Otp can't be empty!"
else:
check_count += 1
# if fname_check, lname_check, pwd_check, otp_check:
if check_count == 5:
if (expectedOtp == enteredOtp):
con = sqlite3.connect('website.db')
c = con.cursor()
c.execute("insert into users VALUES (:fname, :lname, :em, :pwd)",{
'fname': fname.get(),
'lname': lname.get(),
'em': em.get(),
'pwd': pwd.get()
})
con.commit()
ws.destroy()
import app
else:
messagebox.showerror('','Incorrect Otp')
else:
messagebox.showerror('', warn)
<strong># frames</strong>
frame = Frame(ws, padx=20, pady=20)
frame.pack(expand=True)
<strong># labels</strong>
Label(
frame,
text="Create New Account",
font=("Times", "24", "bold")
).grid(row=0, columnspan=3, pady=10)
Label(
frame,
text='First Name',
font=("Times", "14")
).grid(row=1, column=0, pady=5)
Label(
frame,
text='Last Name',
font=("Times", "14")
).grid(row=2, column=0, pady=5)
Label(
frame,
text='Email Address',
font=("Times", "14")
).grid(row=3, column=0, pady=5)
Label(
frame,
text='Password',
font=("Times", "14")
).grid(row=4, column=0, pady=5)
Label(
frame,
text='Enter OTP',
font=("Times", "14")
).grid(row=5, column=0, pady=5)
<strong># Entry</strong>
fname = Entry(frame, width=30)
lname = Entry(frame, width=30)
em = Entry(frame, width=30)
pwd = Entry(frame, width=30)
otp = Entry(frame, width=30)
fname.grid(row=1, column=1)
lname.grid(row=2, column=1)
em.grid(row=3, column=1)
pwd.grid(row=4, column=1)
otp.grid(row=5, column=1)
<strong># button </strong>
clr = Button(frame, text="Clear", padx=20, pady=10, relief=SOLID, font=("Times", "14", "bold"), command=clr)
reg = Button(frame, text="Register", padx=20, pady=10, relief=SOLID, font=("Times", "14", "bold"), command=submit)
ext = Button(frame, text="Exit", padx=20, pady=10, relief=SOLID, font=("Times", "14", "bold"), command=lambda:ws.destroy())
otpp = Button(frame, text="verify email", padx=10, relief=RAISED, font=("Times", "10", "bold"), command=sendOtp)
clr.grid(row=6, column=0, pady=20)
reg.grid(row=6, column=1, pady=20)
ext.grid(row=6, column=2, pady=20)
otpp.grid(row=5, column=2)
ws.mainloop()
output:
In the above code we have made a registration form with details like labels, buttons and entries , this code is connected with a database connection which adds real users to register here.
new account output
In the output below, we fill all the details and verify the email for further action.
Python Tkinter user registration with multiple windows
When we check and randomly enter the OTP, we can see an error is displayed with the message " Incorrect OTP ". This means we can't go any further until we provide the correct OTP and email address used for registration.
Multiple windows in Python tkinter
4. Python Tkinter multi-page access verification
In the next section, we'll look at multi-page access validation.
By access verification, we mean verifying the user's password and email registered during registration. We can also register a user using the create account button in this code.
code:
Login Page.py
Now, let's see some of the libraries we are using in this code are sqlite3 and messagebox under the Tkinter library . Here, labels, fields, entries and buttons are also used.
- un for username
- PD for password
- messagebox.showerror() is used when some incorrect username and password are entered, it will automatically show the error.
from tkinter import *
from tkinter import messagebox
import sqlite3
try:
con = sqlite3.connect('website.db')
c = con.cursor()
c.execute("Select * from users")
for i in c.fetchall():
un = i[2]
pd = i[3]
except Exception as ep:
messagebox.showerror('', ep)
ws = Tk()
ws.title('Python Guides')
ws.geometry('500x400')
ws.config(bg="#447c84")
ws.attributes('-fullscreen',True)
def createAccount():
ws.destroy()
import register
def submit():
u = uname.get()
p = pwd.get()
check_counter=0
if u == "":
warn = "Username can't be empty"
else:
check_counter += 1
if p == "":
warn = "Password can't be empty"
else:
check_counter += 1
if check_counter == 2:
if (u == un and p == pd):
ws.destroy()
import app
else:
messagebox.showerror('', 'invalid username or password')
else:
messagebox.showerror('', warn)
<strong># frame</strong>
frame = Frame(ws, padx=20, pady=20)
frame.pack_propagate(False)
frame.pack(expand=True)
<strong># labels</strong>
Label(
frame,
text="Admin Login",
font=("Times", "24", "bold")
).grid(row=0, columnspan=3, pady=10) #..place(x=170, y=10)
Label(
frame,
text='Enter Username',
font=("Times", "14")
).grid(row=1, column=1, pady=5) #.place(x=50, y=70)
Label(
frame,
text='Enter Password',
font=("Times", "14")
).grid(row=2, column=1, pady=5) #.place(x=50, y=110)
<strong># Entry</strong>
uname = Entry(frame, width=20)
pwd = Entry(frame, width=20, show="*")
# uname.place(x=220, y=70)
# pwd.place(x=220, y=110)
uname.grid(row=1, column=2)
pwd.grid(row=2, column=2)
<strong># button</strong>
reg = Button(
frame,
text="Create Account",
padx=20, pady=10,
relief=RAISED,
font=("Times", "14", "bold"),
command=createAccount
)
sub = Button(
frame,
text="Login",
padx=20,
pady=10,
relief=RAISED,
font=("Times", "14", "bold"),
command=submit
)
reg.grid(row=3, column=1, pady=10)
sub.grid(row=3, column=2, pady=10)
ws.mainloop()
Output:
After running the above code, we got this output in which we can see labels of “enter username”, “enter password” and two-button working on different functionality.
log output
In the output below, we have entered the email in the username and password under the password section and clicked on the Login button.
login window
As we can see, the username and password are entered incorrectly by the user, which shows that it doesn't redirect us to another window or page.
login 2. output
App.py
Below is some code that runs another page after the verification process is complete.
code:
from tkinter import *
from tkinter import messagebox
ws = Tk()
ws.title('Python Guides')
ws.geometry('500x300')
ws.config(bg="#447c84")
ws.attributes('-fullscreen',True)
# functions
def msg():
return messagebox.showinfo('', 'Life is short, \n do what you love')
def logOut():
resp = messagebox.askquestion('', 'Are you sure?')
if resp == 'yes':
ws.destroy()
else:
pass
# frames
frame = Frame(
ws,
padx=20,
pady=20
)
frame.pack(expand=True)
<strong># image </strong>
img = PhotoImage(file='img.png')
<strong># labelslo</strong>
Label(
frame,
text="Congratulations!",
font=("Times", "24", "bold")
).grid(row=0, columnspan=3)
Label(
frame,
text='Your Account is Active',
fg='green',
font=("Times", "14")
).grid(row=1, columnspan=3)
imglbl = Label(frame, image=img)
imglbl.grid(row=2, column=1)
<strong># button</strong>
exp = Button(frame, text="open>>", padx=20, pady=10, relief=SOLID, font=("Times", "14", "bold"), command=msg)
logout = Button(frame, text="Logout", padx=20, pady=10, relief=SOLID, font=("Times", "14", "bold"), command=logOut)
exp.grid(row=2 , column=1)
logout.grid(row=3, column=1)
ws.mainloop()
After running the following code and clicking the "Login " button, we must enter a valid username and password. It will redirect us to another window and show us the following message.
Also, we can see a logout button which will help us exit the page.
output
You may also want to read the following Tkinter tutorials.