How to make a tkinter entry widget for email only - python

I am building a simple login system using Tkinter in python, I want to take user email id by validating the user type value should be a email not anything else. How to make that, please any one tell me.
This is the simple version of my code,
from tkinter import *
root = Tk()
root.geometry("400x300")
def signIn():
if entry_var2.get().isdigit():
print("emailId should not have only numbers")
elif entry_var2.get().isalpha():
print("emailId shold have not only alphabets")
elif entry_var2.get().isspace():
print("emailId don't have space")
else:
print("Login Success") # But it gives not the output I want
# username
entry_var1 = StringVar()
entry1 = Entry(root, textvariable = entry_var1)
entry1.grid(row=0, column=0)
# email id
entry_var2 = StringVar()
entry2 = Entry(root, textvariable = entry_var2)
entry2.grid(row=0, column=0)
# Sign In
button = Button(root, text="Result", command=signIn)
button.grid(row=1, column=0)
root.mainloop()

Use regex to check for email strings.
import re
regex = r'\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
def signIn():
if(re.fullmatch(regex, entry_var2.get())):
print("Valid Email")
else:
print("Invalid Email")

this is python function to validate email using regex:
import re
regex = r'\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
def check(entry_var2):
if(re.fullmatch(regex, entry_var2)):
print("Valid Email")
else:
print("Invalid Email")
for full solution look at this article

Related

SQL code is not comparing variables given by TKinter from within a function

The program I'm currently working on should take two inputs given during a function and use them during another function to verify a user, this is done using Tkinter and SQL but the SQL either throws up an error or does not print or progress at all despite it being coded to do so, currently the result it should give is printing True when the password give and the result of the SQL match, I'm wondering if either the SQL is jankey or the way I've set up the variables is, either way I'm beating my head against trying to figure it out so any help would be appreciated, I'm fairly sure the problem is only with the submitlog fuction if that narrows down any issues.
import sqlite3 #necessary to use databse searching
import os #necessary to check the date listed by the system
from tkinter import * #necessary to use the GUI design features
from tkinter import messagebox #needed for message boxes
login = False #needed to start the login procedure
root =Tk() #defines the foundations for a created page
connection1 = sqlite3.connect("Login.db") #code to read the database and allow crossreferencing of passwords
#connection2
Username = ""
Password = ""
def submitlog(): #a function that will compare and entered username and password with present passwords on the login database
cursor1 = connection1.cursor()
for row in cursor1.execute('SELECT Password FROM Login WHERE Username = "{}"'.format(Username.replace('"','""')), (Username))[0]:
if row == Password:
print(True)
else:
print(Username)
print(Password)
print(row)
def logOut():
root.destroy
exit()
def loginpage(): #defines the creation of a login page
root.geometry("1000x700")
root.resizable(False, False)
root.configure(background = "Black")
#creation of text frames
frame_heading = Frame(root)
frame_heading.grid(row=0, column=0, columnspan=2, padx=30, pady=5)
#creation of entry frames
frame_entry = Frame(root)
frame_entry.grid(row=1, column=0, columnspan=2, padx=10, pady=10)
Label(frame_heading, text="Please log in", font=("Arial", 16)).grid(row=0,column=0,padx=0,pady=5) #heading label
#entry labels
Label(frame_entry, text="Username: ").grid(row=0,column=0,padx=10,pady=10)
Label(frame_entry, text="Password: ").grid(row=1,column=0,padx=10,pady=10)
#text entry fields
UserName = Entry(frame_entry,width=30, bg = "white")
UserName.grid(row=0, column=1, padx=5, pady=5)
PassWord = Entry(frame_entry,width=30, bg = "white")
PassWord.grid(row=1, column=1, padx=5, pady=5)
#placing the submit and log off buttons
submit_button = Button(root, text = "Submit", width =10, command= submitlog)
submit_button.grid(row=2,column=0,padx=0,pady=5)
logout_button = Button(root, text = "Log out", width = 10, command = logOut)
logout_button.grid(row=2,column=1,padx=0,pady=5)
root.mainloop()
Username = UserName.get()
Password = PassWord.get()
return Username and Password
previous attempts to rectify involve me trying to update the variables in both functions as well as running the login page outside of a function but all attempts resulted in either and an error or no activity at all
There's no need to use a for loop. Assuming usernames are unique, the query either returns a row or it doesn't. So you can call cursor1.fetchone() to get that row, then check the password.
You also need to get the username and password from the entry fields when you call submitlog(), not when you first create them.
def submitlog(): #a function that will compare and entered username and password with present passwords on the login database
cursor1 = connection1.cursor()
Username = UserName.get()
Password = PassWord.get()
cursor1.execute('SELECT Password FROM Login WHERE Username = ?', (Username,))
row = cursor1.fetchone()
if row and row[0] == Password:
print(True)
else:
print(Username)
print(Password)
print(row)
You'll need to add global UserName, PassWord to loginpage() so that the variables can be accessed from submitlog().
BTW, return Username and Password is not the way you return multiple values from a function. That should be return Username, Password. But I doubt the return value is used, so you don't need to return anything.
Maybe this helps
query = 'SELECT Password FROM Login WHERE Username = ?'
cursor.execute(query, (Username,))
results = cursor.fetchall()
for row in results:
if row[0] == Password:
print(True)
Thanks Barmar for the helpful comments.

How do i move to another section of my program?

I have built a login system using Tkinter and Sqlite3 for Python and I need to move on to another section of code once the login flow is complete. At the point in the 'test' function where I've added a comment, I need a separate python file (eg somefile.py) to run its code. How is best to do this? Your help is appreciated! Code below:
from tkinter import *
import Check_credentials as check
import New_user_screen as create
def test():
username = user.get()
password = pword.get()
global valid
valid = False
valid=check.check_user(username,password)
print(valid)
if valid == True:
login.destroy()
'launch main program' #Here is where i need the next section of the program to be run but ideally not as another function in this proram
print('Incorrect login getails\nPlease try again!')
def screen():
global login
login = Tk()
login.title('User Login')
login.geometry('300x180')
login.configure(background = 'white')
global user
global pword
message = Label(login,
text = 'Please enter username and password below',
bg='white')
message.pack()
label1 = Label(login,
text = 'Username',
bg='white')
label1.place(x=0,y=50)
user = Entry(login)
user.place(x=100,y=50)
label2 = Label(login,
text = 'Password',
bg='white')
label2.place(x=0,y=90)
pword = Entry(login)
pword.place(x=100,y=90)
confirm = Button(login,
text='Sign In',
fg='white',
bg='blue',
command = test)
confirm.place(x=50,y=130)
new = Button(login,
text='New User',
fg='white',
bg='blue',
command = create.screen)
new.place(x=120,y=130)
When the login is valid, it will go to the the function greeting in the class Main
from tkinter import *
import Check_credentials as check
import New_user_screen as create
class Login:
def test():
username = user.get()
password = pword.get()
global valid
valid = False
valid=check.check_user(username,password)
print(valid)
if valid == True:
login.destroy()
Main.greeting() #Here is where i need the next section of the program to be run but ideally not as another function in this proram
def screen():
global login
login = Tk()
login.title('User Login')
login.geometry('300x180')
login.configure(background = 'white')
global user
global pword
message = Label(login,
text = 'Please enter username and password below',
bg='white')
message.pack()
label1 = Label(login,
text = 'Username',
bg='white')
label1.place(x=0,y=50)
user = Entry(login)
user.place(x=100,y=50)
label2 = Label(login,
text = 'Password',
bg='white')
label2.place(x=0,y=90)
pword = Entry(login)
pword.place(x=100,y=90)
confirm = Button(login,
text='Sign In',
fg='white',
bg='blue',
command = test)
confirm.place(x=50,y=130)
new = Button(login,
text='New User',
fg='white',
bg='blue',
command = create.screen)
new.place(x=120,y=130)
class Main:
def greeting():
print("You Have Logged In Successfully")

Why does python show "TclError : can't invoke "place" command: application has been destroyed" in the following code

import tkinter as tk
def close_window():
print ("")
window.destroy()
window = tk.Tk()
window.geometry("750x350")
username = tk.Label(window, text = "Enter Username")
password = tk.Label(window, text = "Enter Password")
input1 = tk.Entry(window)
input2 = tk.Entry(window, show = "*")
confirm = tk.Button(text="Confirm", command = close_window())
input1.place(x=400, y=35)
input2.place(x=400, y=65)
username.place(x=150, y=35)
password.place(x=150, y=65)
confirm.place(x=400, y=100)
confirm.pack()
window.mainloop()
I am trying to make a forum which closes itself once you click confirm. Also, i use spyder (just in case) and i have just started the concept of tkinter. I tried to find the answer on google but it was not so successful.
you're calling "close_window()" in this line: "confirm = tk.Button(text="Confirm", command = close_window()) "

defined code executes before called upon using tkinter button [duplicate]

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 2 years ago.
I am working on a program that lets users store their usernames and passwords, and hashes the plaintext where they are stored (hence the commented out hashing code). However, I am using tkinter for the GUI, and one of my buttons runs a defined function before it's called. (ignore all seemingly random comments please)
import basehash
import tkinter
import tkinter as tk
import os
from tkinter import*
from tkinter import messagebox
from string import ascii_lowercase
userPaths = ['./usernames2.txt', './username.txt', './usernames3.txt']
passPaths = ['./Passwords2.txt', './Passwords.txt', './Passwords3.txt']
#create new doc and assign doc array
# use an array for password of paths where the password is stored on a plaintext file
password = ("test")
usernameguess1 = ("")
passwordguess1 = ("")
loggedin = 0
activeUser = ""
activeUserNum = 0
hashbase = basehash.base52()
LETTERS = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=1)}
def alphabet_position(text):
text = text.lower()
numbers = [LETTERS[character] for character in text if character in LETTERS]
return ''.join(numbers)
def loginpage():
#Gui Formatting
root = tkinter.Toplevel()
root.resizable(width=FALSE, height=FALSE)
root.title("HasherTest_V0.1 Login")
root.geometry("300x150")
#Username and password boxes
usernametext = tkinter.Label(root, text="Username:")
usernameguess = tkinter.Entry(root)
passwordtext = tkinter.Label(root, text="Password:")
passwordguess = tkinter.Entry(root, show="*")
usernameguess1 = usernameguess
def trylogin():
print ("Logging In...")
for x in range(0,len(userPaths)):
#get path data here
file1 = open(userPaths[x], "r")
original = file1.read()
file1.close()
if original == usernameguess.get():
userPaths[x] = activeUser
x = activeUserNum
file1 = open(passPaths[activeUserNum], "r")
original = file1.read()
original = hashbase.unhash(original)
file1.close()
if usernameguess.get() == activeUser and alphabet_position(passwordguess.get()) == original:
print ("Success!")
messagebox.showinfo("Success ", "Successfully logged in.")
viewbutton = tkinter.Button(root, text="Veiw Saved Passwords", command=lambda:[root.withdraw()])
viewbutton.pack()
else:
print ("Error: (Incorrect value entered)")
messagebox.showinfo("Error", "Sorry, but your username or password is incorrect. Try again")
#login button
def viewtest():
if loggedin == 1:
messagebox.showinfo("Success ", "Loading Passwords")
else:
messagebox.showinfo("Error", "You need to sign in first!")
#login button
root.deiconify() #shows login window
attemptlogin = tkinter.Button(root, text="Login", command=trylogin)
attemptview = tkinter.Button(root, text="View Stored Passwords", command=viewtest)
usernametext.pack()
usernameguess.pack()
passwordtext.pack()
passwordguess.pack()
attemptlogin.pack()
attemptview.pack()
window.mainloop()
def signuppage():
root2 = tkinter.Toplevel()
root2.resizable(width=FALSE, height=FALSE)
root2.title("HasherTest_V0.1 Login")
root2.geometry("300x150")
#Gui Formatting (again)
root2 = tkinter.Tk()
root2.resizable(width=FALSE, height=FALSE)
root2.title("HasherTest_V0.1")
root2.geometry("300x150")
#Username and password boxes
masterusername = tkinter.Label(root2, text="Enter Master Username:")
masterusernamebox = tkinter.Entry(root2)
masterpassword = tkinter.Label(root2, text="Enter Master Password:")
masterpasswordbox = tkinter.Entry(root2, show="*")
def trysignup():
newuser = str(masterusernamebox.get())
length = len(userPaths)
namepath = './usernames3.txt'
userPaths[length-1] = namepath
newfile = open(namepath, 'w')
newfile.write(newuser)
newfile.close()
password = str(masterpasswordbox.get())
numPass = alphabet_position(password)
print(numPass)
"""hashbase = basehash.base52()
#not taking numPass as an int
#run test 328-i
hashval = hashbase.hash(numPass)
print(hashval)
unhashed = hashbase.unhash(hashval)
print(unhashed)"""
path = './passwords3.txt'
newfile = open(path, 'w')
newfile.write(numPass)
newfile.close()
if newuser == "":
messagebox.showinfo("Error code 0", "No input entered")
else:
return
#login button
mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup())
mastersignupbutton.pack()
masterusername.pack()
masterusernamebox.pack()
masterpassword.pack()
masterpasswordbox.pack()
window.mainloop()
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1")
window.geometry("300x150")
loginbutton = tkinter.Button(window, text="Login", command=lambda:[window.withdraw(), loginpage()])
signupbutton = tkinter.Button(window, text="Sign Up", command=lambda:[window.withdraw(), signuppage()])
loginbutton.pack()
signupbutton.pack()
window.mainloop()
If you run this code, and press the sign up button, then type in a master username and password, it should write them both to a notepad file, and if there is nothing in the box, give an error message. However, neither of these functions are working. When the user presses the first "sign up" button on the main window, it runs the wrong code (somehow) and gives an error code before it should. the error code should show if there is nothing there when "sign up 1" button is pressed on the "enter master username and password" window. I have no clue why the code runs early. Could somebody please reply with the reason why, or even some fixed code? thanks, Tf0R24.
When creating a button, a common error is including the parentheses after the function name. Instead of this:
mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup())
Do this:
mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup)
which is exactly the same but without the parentheses after command=trysingup. If you want to call a function that requires arguments, do this:
tkinter.Button(master, text="text", command=lambda: function_that_requires_arguments(x, y))
change to
mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup)

How to create password system in tkinter reading the data from file

I want to create password system in tkinter with notepad as my DB which contains the data in my working directory but when I insert data in the entry fields I receive an error login failed.Have created the txt file but it seems the function can't read from the file.Any suggestion on how to do this.
import tkinter as tk
import sys
from tkinter import messagebox
now = open("passdoc.txt","w+")
now.write("user\n")
now.write("python3")
now.close()
def login_in():
with open("passdoc.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if entry1.get() == new[0] in passdoc.txt and entry2.get() == new[1] in
passdoc.txt:
root.deiconify()
log.destroy()
else:
messagebox.showerror("error","login Failed")
def close():
log.destroy() #Removes toplevel window
root.destroy() #Removes root window
sys.exit() #Ends the script
root=tk.Tk()
log = tk.Toplevel() #
root.geometry("350x350")
log.geometry("200x200")
entry1 = tk.Entry(log) #Username entry
entry2 = tk.Entry(log) #Password entry
button1 = tk.Button(log, text="Login", command=login_in) #Login button
button2 = tk.Button(log, text="Cancel", command=close) #Cancel button
label1 = tk.Label(root, text="tkinter password system")
entry1.pack()
entry2.pack()
button1.pack()
button2.pack()
label1.place(x=30,y=300)
label = tk.Label(root, text="welcome").pack()
root.withdraw()
root.mainloop()
I created this functions too but all seems not to work out for me
def login_in():
with open("passdoc.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if entry1.get() == name in passdoc.txt and entry2.get() == password in
passdoc.txt:
root.deiconify()
log.destroy()
else:
messagebox.showerror("errror","login failed") #error login failed
(corrections)
You have a few things in your code that need some work but the main issue is in your login_in() function.
Your if statement is all wrong. I am not sure why you wrote it the way you did but lets fix it.
Because you defined name = new[0].rstrip() and password = new[1].rstrip()
you can use name and password to verify if the user has enter the correct credentials.
So your if statement should look like this:
if entry1.get() == name and entry2.get() == password:
Your use of in passdoc.txt does not do anything and cannot work because passdoc.txt to python looks like an undefined variable and would fail on the if statement. Remember that you imported all the contents of passdoc.txt as f so you didn't create a variable named passdoc you created one named f for the with open() statement
If you wanted to shorten your code a little you could remove name and password variables and just write the if statement with new
So your login_in() function could look like either this:
def login_in():
with open("passdoc.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if entry1.get() == name and entry2.get() == password:
root.deiconify()
log.destroy()
else:
messagebox.showerror("error","login Failed")
Or this:
def login_in():
with open("passdoc.txt") as f:
new = f.readlines()
if entry1.get() == new[0].rstrip() and entry2.get() == new[1].rstrip():
root.deiconify()
log.destroy()
else:
messagebox.showerror("error","login Failed")

Categories