Im having an issue with my logical/if/else statements it seems! the issue lies where if I type in a wrong password lets say but correct username, nothing happens, similar happens for both student and teacher, im just not really sure what to change. Thank you.
error:
File "/Users/Sebastian/Desktop/DQS/login.py", line 43, in _login_btn_clickked
if ( student_usernames.index(username) == student_passwords.index(password) ):
ValueError: tuple.index(x): x not in tuple
from tkinter import *
import tkinter.messagebox as tm
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.label_1 = Label(self, text="Username")
self.label_2 = Label(self, text="Password")
self.entry_1 = Entry(self)
self.entry_2 = Entry(self, show="*")
self.label_1.grid(row=0, sticky=E)
self.label_2.grid(row=1, sticky=E)
self.entry_1.grid(row=0, column=1)
self.entry_2.grid(row=1, column=1)
self.checkbox = Checkbutton(self, text="Keep me logged in")
self.checkbox.grid(columnspan=2)
self.logbtn = Button(self, text="Login", command = self._login_btn_clickked)
self.logbtn.grid(columnspan=2)
self.pack()
def _login_btn_clickked(self):
#print("Clicked")
username = self.entry_1.get()
password = self.entry_2.get()
#print(username, password)
student_usernames = ("C100", "C200", "C300")
student_passwords = ("PASS", "PASS1", "PASS2")
teacher_usernames = ("T100", "T200", "T300")
teacher_passwords = ("TPASS", "TPASS1", "TPASS3")
if username in student_usernames:
if ( student_usernames.index(username) == student_passwords.index(password) ):
tm.showinfo("Login info", "Welcome Student")
else:
tm.showerror("Login error", "Incorrect information")
elif username in teacher_usernames:
if ( teacher_usernames.index(username) == teacher_passwords.index(password) ):
tm.showinfo("Login info", "Welcome Teacher")
else:
tm.showerror("Login error", "Incorrect information")
else:
tm.showerror("Login error", "Incorrect information")
root = Tk()
lf = LoginFrame(root)
root.mainloop()
student_passwords.index(password) assumes that password actually exists in student_passwords. You could use if username in student_usernames and password in student_passwords: instead or surround the whole block with try: except ValueError:
E.g.
if username in student_usernames and password in student_passwords:
if ( student_usernames.index(username) == student_passwords.index(password) ):
tm.showinfo("Login info", "Welcome Student")
else:
tm.showerror("Login error", "Incorrect information")
elif username in teacher_usernames and password in teacher_passwords:
if ( teacher_usernames.index(username) == teacher_passwords.index(password) ):
tm.showinfo("Login info", "Welcome Teacher")
else:
tm.showerror("Login error", "Incorrect information")
else:
tm.showerror("Login error", "Incorrect information")
You're assuming that the input password will always be in one of the tuples you've defined to contain the password. You can easily break this, simply pass in something that's not contained in one of the tuples. You're condition breaks because as you see in the error message it's trying to find the index of that value but it's not even in the tuple. Hence, the ValueError exception.
You need to check if the password is in the respective student/teacher passwords tuple as well as username, then you can check the indexes.
So, this would be if username in student_usernames and password in student_passwords: as one example.
Or, you could reverse the logic by DeMorgan's Law(s) and use:
if not (username in student_usernames or password in student_passwords)
Related
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.
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
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm working on a password manager using python in the PyCharm IDE. I am working with a database to store the passwords, which makes a .db file in the project folder. Then i wanted to clear that file as i wanted a clear db to work with. So i deleted the .db file from my folder, thinking it would create a new file and work fine. However, it did not.
I get the following error message:
Traceback (most recent call last):
File "C:/Users/Gebruiker/PycharmProjects/evault/main.py", line 246, in <module>
open_vault()
File "C:/Users/Gebruiker/PycharmProjects/evault/main.py", line 235, in open_vault
Label(vault, text=(array[i][1]), font=("Helvetica", 12)).place(x=400, y=400)
IndexError: list index out of range
I tried reverting changes with local history, but that wouldn't work for me either (or i just didn't understand)
[EDIT] Does it maybe have something to do with a new, so empty, database being created and then trying to display the contents of that database but failing as there are none? The deleted database file by me had contents, which did display. Might also be completely wrong, idk.
If it would help, this is my whole project code:
from tkinter import *
from tkinter import messagebox
from random import choice
import array
import sqlite3
import hashlib
import pyperclip as pc
from functools import partial
# Database
with sqlite3.connect("vault.db") as db:
cursor = db.cursor()
service = None
username = None
password = None
cursor.execute("""
CREATE TABLE IF NOT EXISTS vault (
id INTEGER PRIMARY KEY,
service TEXT NOT NULL,
username TEXT NOT NULL,
password TEXT NOT NULL);
""")
def hash_password(pw):
hash = hashlib.md5(pw)
hash = hash.hexdigest()
return hash
def validate_login():
# getting form data
uname = username_log.get()
pwd = master_key.get()
# applying empty validation
if uname == '' or pwd == '':
message.set("Please fill in all the fields")
else:
if uname == "Laurens" and pwd == "password":
login_screen.destroy()
open_vault()
else:
message.set("Wrong username or password")
def generate_password():
len = 12
digits = '0123456789'
chars = 'abcdefghijklmn' \
'opqrstuvwxyz'
up = chars.upper()
special = '_!$%&?'
all = digits + chars + up + special
password = ''.join(
choice(all) for i in range(len)
)
# print out password
print(password)
save = messagebox.askyesnocancel("Generated password", f"Your generated safe password is: \n \n {password} "
f"\n \n Click yes to copy to clipboard"
f"\n and click no to generate a new password.")
if save:
# 'Yes' > copy to clipboard
pc.copy(password)
elif not save and save is not None:
# 'No' > generate new password
generate_password()
else:
# 'Cancel'
pass
def save_credentials():
service_input = service.get()
username_input = username.get()
password_input = password.get()
insert_fields = ("""INSERT INTO vault(service, username, password)
VALUES(?, ?, ?)
""")
cursor.execute(insert_fields, (service_input, username_input, password_input))
db.commit()
print(db)
open_vault()
def remove_credentials(input):
cursor.execute("DELETE FROM vault WHERE id = ?", (input,))
db.commit()
open_vault()
def register_credentials():
global service
global username
global password
vault.destroy()
register_screen = Tk()
register_screen.resizable(False, False)
register_screen.title("Login")
register_screen.geometry("350x500")
register_screen.configure(bg='#212121')
service = StringVar()
username = StringVar()
password = StringVar()
# Service Label
Label(register_screen, text="Name of service: ", bg='#212121', fg='#ABABAB').place(relx=0.5, y=100, anchor=CENTER)
# Service textbox
Entry(register_screen, textvariable=service).place(width=180, height=30, relx=0.5, y=140, anchor=CENTER)
# Username Label
Label(register_screen, text="Username: ", bg='#212121', fg='#ABABAB').place(relx=0.5, y=200, anchor=CENTER)
# Username textbox
Entry(register_screen, textvariable=username).place(width=180, height=30, relx=0.5, y=240, anchor=CENTER)
# Password Label
Label(register_screen, text="Password: ", bg='#212121', fg='#ABABAB').place(relx=0.5, y=300, anchor=CENTER)
# Password textbox
Entry(register_screen, textvariable=password).place(width=180, height=30, relx=0.5, y=340, anchor=CENTER)
# Generate password button
Button(register_screen, text="Generate safe password", bg='#ABABAB', fg='#000000', command=generate_password).place(
width=140, height=30, relx=0.5, y=400, anchor=CENTER)
# Save credentials button
Button(register_screen, text="Save credentials", bg='#673AB7', fg='#FFFFFF', command=save_credentials).place(
width=150, height=40, relx=0.5, y=460, anchor=CENTER)
register_screen.mainloop()
def login_screen():
global login_screen
global message
global username_log
global master_key
login_screen = Tk()
login_screen.resizable(False, False)
login_screen.title("Login")
login_screen.geometry("300x210")
login_screen.configure(bg='#212121')
# declaring variable
username_log = StringVar()
master_key = StringVar()
message = StringVar()
# Creating layout of login form
Label(login_screen, width="300", text="Please enter username and master key", bg="#673AB7", fg="#FFFFFF").pack()
# Username Label
Label(login_screen, text="Username: ", bg='#212121', fg='#ABABAB').place(x=20, y=40)
# Username textbox
Entry(login_screen, textvariable=username_log).place(x=90, y=42)
# Password Label
Label(login_screen, text="Master key: ", bg='#212121', fg='#ABABAB').place(x=20, y=80)
# Password textbox
Entry(login_screen, textvariable=master_key, show="*").place(x=90, y=82)
# Label for displaying login status[success/failed]
Label(login_screen, text="", textvariable=message, bg='#212121', fg='#ff0000').place(relx=0.5, y=125, anchor=CENTER)
# Login button
Button(login_screen, text="Login", width=10, height=1, bg='#673AB7', fg='#FFFFFF', command=validate_login).place(
x=110, y=150)
login_screen.mainloop()
def open_vault():
global vault
vault = Tk()
vault.resizable(False, False)
vault.title("Evault")
vault.geometry("750x500")
vault.configure(bg='#212121')
Label(vault, text="Service", bg='#212121', fg='#ABABAB').place(relx=0.2, y=75)
Label(vault, text="Username", bg='#212121', fg='#ABABAB').place(relx=0.45, y=75)
Label(vault, text="Password", bg='#212121', fg='#ABABAB').place(relx=0.7, y=75)
Button(vault, text="Register new credentials", bg='#673AB7', fg='#FFFFFF', command=register_credentials).place(
width=150, height=40, relx=0.5, y=450, anchor=CENTER)
cursor.execute('SELECT * FROM vault')
if cursor.fetchall() != None:
i = 0
while True:
cursor.execute('SELECT * FROM vault')
array = cursor.fetchall()
Label(vault, text=(array[i][1]), font=("Helvetica", 12)).place(x=400, y=400)
i += 1
cursor.execute('SELECT * FROM vault')
if len(cursor.fetchall()) <= i:
break
vault.mainloop()
open_vault()
The error is being thrown by this:
cursor.execute('SELECT * FROM vault')
if cursor.fetchall() != None:
i = 0
while True:
cursor.execute('SELECT * FROM vault')
array = cursor.fetchall()
Label(vault, text=(array[i][1]), font=("Helvetica", 12)).place(x=400, y=400)
i += 1
cursor.execute('SELECT * FROM vault')
if len(cursor.fetchall()) <= i:
break
I confess I don't understand what this code is supposed to do. Why does it repeatedly execute the same query? You probably want something like this:
cursor.execute("SELECT * FROM vault")
START_HEIGHT=400
LINE_HEIGHT=50
for i, row in enumerate(cursor.fetchall()):
line_pos = START_HEIGHT + i * LINE_HEIGHT
Label(vault, text=row[1]).place(x=400,y=line_pos)
i.e. just iterate over the rows returned by the cursor directly.
If that is still throwing an error, you need to do some debugging: print what cursor.fetchall() actually returns. (Specifically, print list(cursor.fetchall()) in case it's an iterator.)
I am relatively new to this, but is anyone able to find out why errorLabel is not forgetting? I do not see the reason as to why this would be the case. All of the other widgets disappear, but not the errorLabel.
def checkLogin(root, username, password, userNameLabel, userNameEntry, passwordLabel, passwordEntry, loginButton):
print(gui.checkUser(username, password))
errorLabel = Label(root, text="")
errorLabel.pack()
if (gui.checkUser(username, password)):
userNameLabel.forget()
errorLabel.forget()
userNameEntry.forget()
passwordLabel.forget()
passwordEntry.forget()
loginButton.forget()
else:
errorLabel.config(text="Error, that is an incorrect username and/or password")
This is whole code
class gui:
def checkUser(username, password):
data = musicQuiz.getUsers()
for usernameDB, passwordDB in data:
if str(usernameDB) == str(username) and str(passwordDB) == str(password):
return True
return False
def checkLogin(root, username, password, userNameLabel, userNameEntry, passwordLabel, passwordEntry, loginButton):
print(gui.checkUser(username, password))
errorLabel = Label(root, text="")
errorLabel.pack()
if (gui.checkUser(username, password)):
userNameLabel.forget()
errorLabel.forget()
userNameEntry.forget()
passwordLabel.forget()
passwordEntry.forget()
loginButton.forget()
else:
errorLabel.config(text="Error, that is an incorrect username and/or password")
def login(root):
userNameLabel = Label(root, text="Username")
userNameEntry = Entry(root)
passwordLabel = Label(root, text="Password")
passwordEntry = Entry(root)
loginButton = Button(root, text = "Login!", command=lambda: gui.checkLogin(root, userNameEntry.get(), passwordEntry.get(), userNameLabel, userNameEntry, passwordLabel, passwordEntry, loginButton))
userNameLabel.pack()
userNameEntry.pack()
passwordLabel.pack()
passwordEntry.pack()
loginButton.pack()
def main():
musicQuiz.setupSQL()
root = Tk()
root.geometry("350x350")
gui.login(root)
root.mainloop()
if __name__ == "__main__":
gui.main()
so, i opened a question about it yesterday but it got closed saying its a dupe, let me explain my question more specificly then, hoping im not passinng any law here..
im trying to set a default message that will be set as gray and low opacity in the entry widget on tkinter, that after being focused in will dispear.
i managed to do that, but i got into a problem.
the default text is "enter username" for example, but if someone tries to do this user name it says that the username entry is empty which isnt what i wanna do..
i hope you understood my question.
edit: my question is how to do a placeholder text, while allowing the user to input the same text as the placeholder.
thanks in advance, this is my code:
from tkinter import *
from tkinter import messagebox
main = Tk()
main.title("ani gever")
checkbox_var = IntVar()
def delete_user_default(event):
if User_entry.get()!="enter username":
pass
else:
User_entry.delete(0, END)
def delete_password_default(event):
if password_entry.get() !="insert password":
pass
else:
password_entry.delete(0, END)
password_entry.config(show="*")
def return_user_default(event):
if User_entry.get()=="":
User_entry.insert(0, "enter username")
emptyuser=1
else:
pass
def return_password_default(event):
if password_entry.get()=="":
password_entry.insert(0,"insert password")
password_entry.config(show="")
else:
pass
def details(event):
if ((User_entry.get() == "enter username") or (password_entry.get() == "insert password")):
errorLabel.config(text="Username or password is empty!",fg="red")
elif ((" " in User_entry.get()) or " " in password_entry.get()):
errorLabel.config(text="dont use spaces in your password or username!", fg="red")
else:
print ("username:" + User_entry.get() + "\npassword:" + password_entry.get())
errorLabel.config(text="")
#============== define texts=======================
User_label= Label(main,text="Username:")
password_label= Label(main,text="Password:")
User_entry = Entry(main)
password_entry= Entry(main,show="*")
enterButton= Button(main,text="Log in")
errorLabel= Label(main,text="")
#=============default text on entry's=============
password_entry.config(show="")
User_entry.insert(0,"enter username")
password_entry.insert(0,"insert password")
User_entry.bind("<FocusIn>",delete_user_default)
password_entry.bind("<FocusIn>",delete_password_default)
User_entry.bind("<FocusOut>",return_user_default)
password_entry.bind("<FocusOut>",return_password_default)
#=============return user details ===========
User_entry.bind("<Return>",details)
password_entry.bind("<Return>",details)
enterButton.bind("<Button-1>",details)
#=============place everything on screen===========
User_label.grid(row=0,sticky= W)
User_entry.grid(row=0,column=1,sticky= W)
password_label.grid(row=1,sticky= W)
password_entry.grid(row=1,column=1,sticky= W)
enterButton.grid(row=2,sticky=W)
errorLabel.grid(row=3,columnspan=10,sticky= W)
main.mainloop()
Using this answer an is_empty function can be created. It prints True if validated entry is 'empty' and False if not.
import tkinter as tk
class EntryWithPlaceholder(tk.Entry):
def __init__(self, master=None, placeholder="PLACEHOLDER", color='grey'):
super().__init__(master)
self.placeholder = placeholder
self.placeholder_color = color
self.default_fg_color = self['fg']
self.bind("<FocusIn>", self.foc_in)
self.bind("<FocusOut>", self.foc_out)
self.put_placeholder()
def put_placeholder(self):
self.insert(0, self.placeholder)
self['fg'] = self.placeholder_color
def foc_in(self, *args):
if self['fg'] == self.placeholder_color:
self.delete('0', 'end')
self['fg'] = self.default_fg_color
def foc_out(self, *args):
if not self.get():
self.put_placeholder()
def is_empty(widget, empty_color):
if widget.get():
if widget['fg'] == empty_color:
print (True)
else:
print (False)
else:
print (True)
if __name__ == "__main__":
root = tk.Tk()
username = EntryWithPlaceholder(root, "username")
password = EntryWithPlaceholder(root, "password", 'blue')
username.pack()
password.pack()
tk.Button(root, text="Validate",
command=lambda wid=username, clr=username.placeholder_color:
is_empty(wid, clr)).pack()
root.mainloop()