Hi so basically I want my program to 'log in' whenever i hit the enter key. How would I do this?
My code:
def Login(event=None):
Db() #calls the database function/ subroutine
if USERNAME.get() == "" or PASSWORD.get() == "":
lbl_text.config(text="Please fill in the required details", fg="red", font="Arial")
PASSWORD.set("") #resets the password field to nill (with no username the password field is useless)
else:
cursor.execute("SELECT * FROM `member` WHERE `username` = ? AND `password` = ?", (USERNAME.get(), PASSWORD.get())) #username and password retrieved from database
if cursor.fetchone() is not None:
Home()
PASSWORD.set("") #resets password field to nill, so nobody can log in with same credentials if the log in window is left open
lbl_text.config(text="")
else:
lbl_text.config(text="Incorrect Details entered", fg="red", font="Arial")
PASSWORD.set("") #resets the password field to nill (I don't do the same with the password field, as the password field is typically wrong)
cursor.close()
conn.close()
btn_login = Button(Form, text="Login", width=45, command=Login)
btn_login.grid(pady=25, row=3, columnspan=3)
btn_login.bind('<Return>', Login)
Thanks
You can bind enter to a function in tkinter:
from tkinter import *
window = Tk()
window.geometry("600x400")
window.title("Test")
def test(event):
print("Hi")
window.bind("<Return>", test)
window.mainloop()
Related
Here is where I believe I would put the code for the restrictions
def savePassword():
os.system("Email.py")
if txt.get() == txt1.get():
# encode password for hashing
hashedPassword = hashPassword(txt.get().encode("utf-8"))
# insert masterpassword into database
insert_password = """INSERT INTO masterpassword(password)
VALUES(?) """
cursor.execute(insert_password, [hashedPassword])
sql_command = 'INSERT INTO details (email) VALUES(?) ' # Query
email = txt3.get()
cursor.execute(sql_command, [email])
db.commit()
passwordVault()
else:
lbl2.config(text="Passwords do not match")
i'd like it so that if the password does not reach a length requirement of say 7
Entry widget has validate and validatecommand that can do this job.
Here's an example code:
from tkinter import *
def check(ch):
return len(ch) <= 7 or ch==''
root = Tk()
ent = Entry(root, show='*')
ent.config(validate='key', validatecommand=(root.register(check), "%P"))
ent.pack()
root.mainloop()
update:
from tkinter import *
def savePasswd():
if len(ent.get())>7:
label['text'] = 'saved'
print("saved") # write save stmts here
else:
label['text']="Minimum length 7"
root = Tk()
label = Label(root)
label.pack()
ent = Entry(root, show='*')
ent.pack()
Button(root, text='save password', command=savePasswd).pack()
root.mainloop()
I'm trying to make a GUI for a password storage and hashing system, but I have hit a roadblock. I am having 2 buttons, one to log in, and one to make an account. When the login button is clicked, a new tkinter window opens with the login page. however, the login button is supposed to show on the second page, but it doesn't, and I have no clue why. Here is the code for the full system:
import tkinter
from tkinter import*
username = ("Tom")
password = ("test")
usernameguess1 = ("")
passwordguess1 = ("")
def trylogin():
print ("Trying to login...")
if usernameguess.get() == username:
print ("Complete sucsessfull!")
messagebox.showinfo("Sucess ", "Successfully logged in.")
else:
print ("Error: (Incorrect value entered)")
messagebox.showinfo("Error", "Sorry, but your username or password is incorrect. Try again")
def loginpage():
#Gui Formatting
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1 Login")
window.geometry("300x150")
#Username and password boxes
usernametext = tkinter.Label(window, text="Username:")
usernameguess = tkinter.Entry(window)
passwordtext = tkinter.Label(window, text="Password:")
passwordguess = tkinter.Entry(window, show="*")
usernameguess1 = usernameguess
#login button
attemptlogin = tkinter.Button(text="Login", command=trylogin)
usernametext.pack()
usernameguess.pack()
passwordtext.pack()
passwordguess.pack()
attemptlogin.pack()
window.mainloop()
#Gui Formatting (again)
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1")
window.geometry("300x150")
loginbutton = tkinter.Button(text="Login", command=loginpage)
loginbutton.pack()
And here is the code for just the second window on its own. For some reason I have to import tkinter message boxes aswell, or my IDLE errors out.
import tkinter
from tkinter import *
from tkinter import messagebox
username = ("Tom")
password = ("test")
usernameguess1 = ("")
passwordguess1 = ("")
def trylogin():
print ("Trying to login...")
if usernameguess.get() == username:
print ("Complete sucsessfull!")
messagebox.showinfo("Sucess ", "Successfully logged in.")
else:
print ("Error: (Incorrect value entered)")
messagebox.showinfo("Error", "Sorry, but your username or password is incorrect. Try again")
#Gui Formatting
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1 Login")
window.geometry("300x150")
#Username and password boxes
usernametext = tkinter.Label(window, text="Username:")
usernameguess = tkinter.Entry(window)
passwordtext = tkinter.Label(window, text="Password:")
passwordguess = tkinter.Entry(window, show="*")
usernameguess1 = usernameguess
#login button
attemptlogin = tkinter.Button(text="Login", command=trylogin)
usernametext.pack()
usernameguess.pack()
passwordtext.pack()
passwordguess.pack()
attemptlogin.pack()
window.mainloop()
Thanks for your help!
Here. I completely reworked your code, and it works(as far as I can tell).
I completely removed the textvariable and StringVar(). They aren't needed. The reason your code wasn't working is because you check the name of the file "string", but you need to add ".txt" in order to get a perfect equality.
Code:
import tkinter
from tkinter import*
from tkinter import messagebox
username = ("Tom")
password = ("test")
usernameguess1 = ("")
passwordguess1 = ("")
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 ("Trying to login...")
if usernameguess.get() == username:
print ("Complete sucsessfull!")
messagebox.showinfo("Sucess ", "Successfully logged in.")
else:
print ("Error: (Incorrect value entered)")
messagebox.showinfo("Error", "Sorry, but your username or password is incorrect. Try again")
#login button
attemptlogin = tkinter.Button(root, text="Login", command=trylogin)
usernametext.pack()
usernameguess.pack()
passwordtext.pack()
passwordguess.pack()
attemptlogin.pack()
window.mainloop()
#Gui Formatting (again)
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1")
window.geometry("300x150")
loginbutton = tkinter.Button(window, text="Login", command=loginpage)
loginbutton.pack()
window.mainloop()
I also took the liberty to, as #stovfl mentioned, add Toplevel() instances instead of using Tk() multiple times.
Hope this helps!
my program is meant say 'Accessed granted' if i enter the correct username and password, however regardless of what i type, i keep getting 'Invalid login' can someone point out whats wrong? btw dont worry about it the indentation is wrong, it changes when it put code on this site.
from tkinter import *# Ingress all components from Tkinter
import tkinter.messagebox as box
def dialog1():
username=entry1.get()
password = entry2.get()
if (username == 'admin' and password == 'ad121'):#Correct log in details
box.showinfo('info','Access granted')# correct response
else:
box.showinfo('info','Invalid Login')# decline response
def condition():
while condition == (username == 'admin' and password == 'ad121'):
print = label(text('Welcome back admin user!',bg='Light Blue',font='none 14 bold').place(x=0,y=160))
window = Tk()
window.geometry('400x400')# The size of the form window
window.title('Office login system')#title of the form
frame = Frame(window)
mlabel = Label(text='Log in system', bg='Light Blue',font='none 18 bold underline')# The colours and font style and size used for the form title
mlabel.pack()
Label1 = Label(window,text = 'Username:',bg='Light Blue',font='none 14 bold').place(x=0,y=100)
entry2 = Entry(window).place(x=140,y=108)#Size and colour of the text box
entry1 = Entry(window,bd =5)
entry1.pack
Label2 = Label(window,text = 'Password:',bg='Light Blue',font='none 14 bold').place(x=0,y=150)
entry2 = Entry(window).place(x=140,y=155)#Size and colour of the text box
entry2 = Entry(window, bd=5)
entry2.pack
window.configure(background='Orange')
btn = Button(window, text = 'Check Login',command = dialog1)
btn.place(x=150,y=250)
frame.pack(padx =200,pady =190)
window.mainloop()# The code iterates
You are declaring entry2 multiple times in the scope of your script.
I tried this and it works as you expect.
from tkinter import Button, Entry, Tk
import tkinter.messagebox as box
class GUI:
def __init__(self):
self.root = Tk()
self.username_field = Entry(self.root)
self.password_field = Entry(self.root)
self.username_field.insert(0, "Enter Username")
self.password_field.insert(0, "Enter Password")
self.submit = Button(self.root, text="Submit", command=self.login)
self.username_field.pack()
self.password_field.pack()
self.submit.pack()
def login(self):
username = self.username_field.get()
password = self.password_field.get()
print(username, password)
# The while loop
while username == password:
box.showinfo("info", "Username and password must not match!")
break
if(username == "admin" and password == "ad121"):
box.showinfo("info", "Welcome " + username + "!")
else:
box.showinfo("info", "Invalid credentials")
app = GUI()
app.root.mainloop()
Working on a group program that has users and passwords. We are trying to insert our users and passwords via python to sqlite. But atm we are only sending blank data before our graphic window pops up with a button that is supposed to send the data. We have tried different variations found on multiple websites but nothing seems to work.
from tkinter import *
import sqlite3
import sys
conn = sqlite3.connect('indexCards.db')
cur = conn.cursor()
users ={}
def addUser(entUsername, entPassword):
#global entUsername, entPassword
NAME = entUsername.get()
PASSWORD = entPassword.get()
print("add User") #this is testing only
print(NAME, PASSWORD) # this is testing to see the passed variable
//
//This is where we are having the issues
conn.executemany('INSERT INTO USER(NAME,PASSWORD)\
VALUES (? ,?);', [(NAME,PASSWORD)])
conn.commit();
return (NAME, PASSWORD)
def makeWindow():
global entUsername, entPassword
window = Tk()
window.title('Add New User')
lblInst = Label(window, text = "Create your account here:", font=("Helvetica",16))
lblInst.pack()
lblUsername = Label(window, text="Please enter a username: ")
entUsername = Entry(window)
lblUsername.pack()
entUsername.pack()
lblPassword = Label(window, text="Please enter a password: ")
entPassword = Entry(window)
lblPassword.pack()
entPassword.pack()
btn = Button(window, text="Create", command=addUser(entUsername, entPassword))
btn.pack()
print (addUser(entUsername, entPassword))
print('entUsername', 'entPassword')
#window.mainloop()
return window
#if __name__ == '__main__':
# main():
window = makeWindow()
window.mainloop()
The problem is that you're calling the function immediately, before the user has a chance to enter any data.
See Why is Button parameter “command” executed when declared?
The reason it invokes the method immediately and pressing the button does nothing is that addUser(entUsername, entPassword) is evaluated and its return value is attributed as the command for the button. So if addUser prints something to tell you it has run and returns None, you just run addUser to evaluate its return value and given None as the command for the button.
To have buttons to call functions with different arguments you can use global variables, although I can't recommend it:
import sqlite3
from tkinter import *
conn = sqlite3.connect('indexCards.db')
cur = conn.cursor()
users = {}
cur = conn.cursor()
cur.execute('''
Create table if not exists USER(NAME varchar(100), PASSWORD varchar(100))
''')
def addUser():
NAME = entUsername.get()
PASSWORD = entPassword.get()
print("add User") # this is testing only
print(NAME, PASSWORD) # this is testing to see the passed variable
# This is where we are having the issues
conn.executemany('INSERT INTO USER(NAME,PASSWORD) VALUES (? ,?);', [(NAME, PASSWORD)])
conn.commit()
return (NAME, PASSWORD)
def makeWindow():
global entUsername
global entPassword
window = Tk()
window.title('Add New User')
lblInst = Label(window, text="Create your account here:", font=("Helvetica", 16))
lblInst.pack()
lblUsername = Label(window, text="Please enter a username: ")
entUsername = Entry(window)
lblUsername.pack()
entUsername.pack()
lblPassword = Label(window, text="Please enter a password: ")
entPassword = Entry(window)
lblPassword.pack()
entPassword.pack()
btn = Button(window, text="Create", command=addUser)
btn.pack()
print(addUser())
window.mainloop()
return window
window = makeWindow()
If you don't want to create global then you can pass the function with multiple arguments to an anonymous function i.e lambda function
btn = Button(window, text="Create", command= lambda : addUser(entUsername, entPassword))
In the below code two tkinter entry is created entry1 and entry2 respectively for username and password. What I am looking for is storing the value entered in the tkinter entry to the database table admin_details. But nothing is passed. Also I have no idea in using the condition i.e. " retrieve the values inserted in the tkinter entry and store the data inside the table after the button Login is pressed."
Code is something like below:
import MySQLdb as mdb
from Tkinter import *
from tkMessageBox import *
root = Tk()
test=StringVar()
label1=Label(root,text='Username').grid()
entry1 = Entry(root, textvariable='uname')
entry1.grid()
label2=Label(root,text='password').grid()
entry2 = Entry(root, textvariable='pword')
entry2.grid()
print entry2
uname = entry1.get()
pword= entry2.get()
tup=[uname,pword]
option1 = Button(root, text = 'Login', command = next)
option1.grid()
if uname!='':
def next():
con = mdb.connect('localhost', 'root', 'root', 'kuis');
with con:
cur = con.cursor()
insert_sql = 'INSERT INTO admin_details(username, password) VALUES("{0}","{1}")'.format(*tup)
cur.execute(insert_sql)
root.mainloop()
The obvious problem is you are getting the text from both Entries directly after they have been initialized. The two variables you are using for this will not be changed when the Text in the Entries changes.
Here is some basic code how to retrieve the values from the two entry fields and pass them to a function:
import tkinter as Tk
import tkinter.messagebox
def show_pass_user(password, user):
# show what we got
tkinter.messagebox.showinfo("Data received", "Hey just got your username \"" + user + "\"" +
" and password \"" + password + "\"")
# run your sql here
def main():
root = Tk.Tk()
entry_user = Tk.Entry(root)
entry_user.insert(0, "Username")
entry_pass = Tk.Entry(root)
entry_pass.insert(0, "Password")
# use a lambda to get Username and Password when button is pressed
pressme = Tk.Button(root, text="Press Me", command=lambda:
show_pass_user(entry_pass.get(), entry_user.get()))
entry_user.grid()
entry_pass.grid()
pressme.grid()
root.mainloop()
if __name__ == "__main__":
main()
This code runs only with Python3!