import pickle
from tkinter import *
import tkinter.messagebox
Menu = Tk()
Menu.resizable(width=False, height = False)
Menu.state('zoomed')
Menu.title("Gold Farm")
Example = {"Test":"Initial"}
def database():
with open ("accounts.pickle", "rb") as f:
return pickle.load(f)
accounts = database()
usernameL = Label(text = "Username: ")
usernameL.place(y= 300, x = 550)
usernameB = Entry()
usernameB.place(y = 300,x = 620)
passwordL = Label(text = "Password: ")
passwordL.place(y= 330, x = 550)
passwordB = Entry(show = "*")
passwordB.place(y = 330,x = 620)
eUsername = usernameB.get()
ePassword = passwordB.get()
def confirm():
for item in accounts:
if eUsername in accounts and accounts[eUsername] == ePassword:
print("Correct")
else:
print("False")
Login = Button(text="Login", command = confirm)
Login.place(y = 350, x = 620)
This is my code that completes the following:
Asks the user for a username and password in a tkinter window
Sets whatever they inputted as eUsername and ePassword
Checks if they got the right password
Keep in mind that the 'Example' dictionary is an example of what is in the accounts files
The problem is that when I type in the correct username and password, it still returns as false.
And so;
I would like some assistance on what I'm doing wrong, or what to fix.
Test
def databaseNew():
with open("accounts.pickle", "wb") as f:
Entry = Setup["me"] = "Tes"
pickle.dump(Entry, f)
You are not getting any input in your code, if you call confirm() you will see False as you are iterating over every name in the dict with for item in accounts comparing it to an empty string. You can also simplify your function to return accounts.get(eUsername) == ePassword to check:
def confirm():
print(accounts.get(eUsername) == ePassword)
You need to pack the Labels etc..
import pickle
from tkinter import *
master = Tk()
usernameL = Label(master, text="Username: ")
usernameL.pack()
usernameB = Entry(master)
usernameB.pack()
passwordL = Label(master, text="Password: ")
passwordL.pack()
passwordB = Entry(master, show="*")
passwordB.pack()
master.resizable(width=False, height=False)
master.state('normal')
master.title("Gold Farm")
def database():
with open("accounts.pickle", "rb") as f:
return pickle.load(f)
accounts = database()
def confirm():
u, p = usernameB.get(), passwordB.get()
if accounts.get(u) == p:
print(True)
# do whatever here
else:
print(False)
# login is bad
m = messagebox.askretrycancel("Invalid input")
if not m:
master.quit()
Login = Button(master, text="Login", command=confirm)
Login.place(y=350, x=620)
Login.pack()
mainloop()
This is a rough example of how to add new users to your existing dict and pickle, you can fill in the missing logic and tidy up the display with whatever you have planned and verify input:
import pickle
from tkinter import *
master = Tk()
usernameL = Label(master, text="Username: ")
usernameL.pack()
usernameB = Entry(master)
usernameB.pack()
passwordL = Label(master, text="Password: ")
passwordL.pack()
passwordB = Entry(master, show="*")
passwordB.pack()
master.resizable(width=False, height=False)
master.state('normal')
master.title("Gold Farm")
def database():
with open("accounts.pickle", "rb") as f:
return pickle.load(f)
accounts = database()
def new():
u, p = usernameB.get(), passwordB.get()
if u in accounts:
m = messagebox.askretrycancel("Invalid","Username taken")
if not m:
master.quit()
else:
accounts[u] = p
with open("accounts.pickle","wb") as f:
pickle.dump(accounts, f)
# do whatever
def confirm():
u, p = usernameB.get(), passwordB.get()
if accounts.get(u) == p:
print(True)
# do whatever here
else:
print(False)
# do whatever when login is bad
m = messagebox.askretrycancel("Invalid input")
if not m:
master.quit()
Login = Button(master, text="Login", command=confirm)
Login.place(y=350, x=620)
Login.pack()
new_user = Button(master, text="Create acc", command=new)
new_user.pack()
mainloop()
Related
When I write the informations into input sections and click to button, the program printing [] part no matter if infos match with the true conditions. I think my "def" function or .get() system is wrong but I couldn't find any correct way on the net.
from os import defpath
from tkinter import *
#from PIL import ImageTk,Image
root = Tk()
root.geometry("400x400")
username = ["Enes"]
age = ["19"]
password = ["Bruh"]
username_g = []
age_g = []
passwork_g = []
response = Entry(root)
response.pack()
response2 = Entry(root)
response2.pack()
response4 = Entry(root)
response4.pack()
def loginbruh():
#response.get()
#response2.get()
#response3.get()
#response4.get()
username_g + [response.get()]
age_g + [response2.get()]
password_g + [response4.get()]
if password_g == password and age_g == age and username_g == username:
print("Doğru girdiniz")
else:
print(password_g)
login_button = Button(root, text="Login", command=loginbruh)
login_button.pack()
root.mainloop()
I remove the lists and directly used .get(), it worked!
from os import defpath
from tkinter import *
#from PIL import ImageTk,Image
root = Tk()
root.geometry("400x400")
username = "Enes"
age = "19"
password = "Bruh"
response = Entry(root)
response.pack()
response2 = Entry(root)
response2.pack()
response4 = Entry(root)
response4.pack()
def loginbruh():
#response.get()
#response2.get()
#response3.get()
#response4.get()
if response4.get() == password and str(response2.get()) == age and response.get() == username:
print("Doğru girdiniz")
else:
print(response.get())
login_button = Button(root, text="Login", command=loginbruh)
login_button.pack()
root.mainloop()
I've been experimenting with a sqlite3 for the first time and was developing a login system (with some help from articles and videos) and have noticed that all credentials inputted into the program are being accepted, I can't find a fault in the program so I could use some help.
Importing Important Libraries
import sqlite3
import bcrypt
class Database:
def __init__(self):
try:
self.conn = sqlite3.connect("usertable.db")
print("Successfully Opened Database")
self.curr = self.conn.cursor()
except:
print("Failed")
def createTable(self):
create_table = '''
CREATE TABLE IF NOT EXISTS cred(
id Integer PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
);
'''
self.curr.execute(create_table)
self.conn.commit()
def insertData(self, data):
insert_data = """
INSERT INTO cred(username, password)
VALUES(?, ?);
"""
self.curr.execute(insert_data, data)
self.conn.commit()
def searchData(self, data):
search_data = '''
SELECT * FROM cred WHERE username = (?);
'''
self.curr.execute(search_data, data)
rows = self.curr.fetchall()
if rows == []:
return 1
return 0
def validateData(self, data, inputData):
validate_data = """
SELECT * FROM cred WHERE username = (?);
"""
self.curr.execute(validate_data, data)
row = self.curr.fetchall()
if row[0][1] == inputData[0]:
return row[0][2] == bcrypt.hashpw(inputData[1].encode(), row[0][2])
(The login and register classes)
from tkinter import *
from tkinter import messagebox
import bcrypt
from database import Database
db = Database()
db.createTable()
class Login:
def __init__(self):
self.loginWindow = Tk()
self.loginWindow.title("Login")
self.loginWindow.geometry("300x250")
self.label = Label(self.loginWindow, text="Login")
self.label.place(x=95, y=40)
self.usernames = StringVar()
self.passwords = StringVar()
self.usernameE = Entry(self.loginWindow, relief=FLAT, textvariable=self.usernames)
self.usernameE.place(x=70, y=80)
self.passwordE = Entry(self.loginWindow, show="*", relief=FLAT, textvariable = self.passwords)
self.passwordE.place(x=70, y=120)
self.username = self.usernames.get()
self.password = self.passwords.get()
self.submit = Button(self.loginWindow, text = "Submit", pady = 5, padx = 20, command = self.validate)
self.submit.place(x=100, y=150)
def validate(self):
data = (self.username,)
inputData = (self.username, self.password,)
try:
if (db.validateData(data, inputData)):
messagebox.showinfo("Successful", "Login Was Successful")
else:
messagebox.showerror("Error", "Wrong Credentials")
except IndexError:
messagebox.showerror("Error", "Wrong Credentials")
def run(self):
self.loginWindow.mainloop()
class Register:
def __init__(self):
self.registerWindow = Tk()
self.registerWindow.title("Register")
self.registerWindow.geometry("300x250")
self.label = Label(self.registerWindow, text="Register")
self.usernameS = StringVar()
self.passwordS = StringVar()
self.usernameE = Entry(self.registerWindow, relief = FLAT, textvariable = self.usernameS)
self.usernameE.place(x=70, y=80)
self.passwordE = Entry(self.registerWindow, show="*", relief = FLAT, textvariable = self.passwordS)
self.passwordE.place(x=70, y=120)
self.submit = Button(self.registerWindow, text="Submit", pady = 5, padx = 20, command = self.add)
self.submit.place(x=100, y=150)
self.username = self.usernameS.get()
self.password = self.passwordS.get()
self.salt = bcrypt.gensalt()
self.hashed = bcrypt.hashpw(self.password.encode(), self.salt)
def run(self):
self.registerWindow.mainloop()
def add(self):
data = (self.username,)
result = db.searchData(data)
print(result, result, result)
if result != 0:
data = (self.username, self.hashed)
db.insertData(data)
messagebox.showinfo("Successful", "Username Was Added")
else:
messagebox.showwarning("Warning", "Username already Exists")
(The main window class)
from tkinter import *
from login import Login, Register
class Window(object):
def __init__(self):
self.window = Tk()
self.window.title("Login Screen")
self.window.geometry("300x250")
self.label = Label(self.window, text = "Welcome to Login")
self.label.place(x=95, y=40)
self.login = Button(self.window, text = "Login", pady = 5, padx = 30, command = login)
self.login.place(x=100, y=100)
self.register = Button(self.window, text = "Register", pady = 5, padx = 20, command = register)
self.register.place(x=100, y=150)
def run(self):
self.window.mainloop()
def login():
loginTk = Login()
loginTk.run()
def register():
registerTk = Register()
registerTk.run()
window = Window()
window.run()
The program is stored in 3 different files (the login and register classes are stored within the same file.)
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)
Here's my entire code:
import tkinter as tk
from tkinter import *
import turtle
file = open("usernames.txt", "r+")
file2 = open("passwords.txt", "r+")
def mainScreen():
mainScreen = Tk()
mainScreen.geometry("250x175")
mainScreen.title("Login Screen")
Label(text = "Please select an option.").pack()
Label(text = "").pack()
Button(text = "Login into an existing account.", command = login).pack()
Label(text = "").pack()
Button(text = "Create a new account.").pack()
mainScreen.mainloop()
def login():
loginScreen = Tk()
loginScreen.geometry("200x150")
loginScreen.title("Existing Account Login")
Label(loginScreen,text = "Please enter your username.").pack()
eUserName = StringVar()
userEntry = Entry(loginScreen, textvariable = eUserName)
userEntry.pack()
eUserName = userEntry.get()
Label(loginScreen,text = "Please enter your pasword.").pack()
ePassWord = StringVar()
passEntry = Entry(loginScreen, textvariable = ePassWord)
passEntry.pack()
ePassWord = passEntry.get()
Label(text="").pack()
Button(loginScreen, text = "Click to login.", command = authenticate_name).pack()
return ePassWord, eUserName
def authenticate_name(eUsername):
usernames = []
validCheck = False
for line in file:
usernames.append(line)
for eUserName in usernames:
if eUserName in usernames:
validCheck = True
pass
else:
tkMessageBox.showerror("Invalid Username!", "This usernames is invalid!")
exit()
def authenticate_password():
passwords = []
for line in file2:
passwords.append(line)
for count in range(len(passwords)):
count += 1
if ePassWord in passwords:
game()
else:
tkMessageBox.showerror("Invalid Password!", "This password is incorrect!")
mainScreen()
The error I get is the following:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Vlad\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
TypeError: authenticate_name() missing 1 required positional argument: 'eUsername'
I don't know how to fix this. I've tried doing an str() function on eUsername and that didn't seen to work.
Any help would be greatly appreciated!
You're using a number of features of (Python 3) tkinter incorrectly, including StringVar, messagebox, top level windows, etc. By making your StringVar variables global, and reworking your logic, I've come up to this approximation to what you're trying to implement:
from tkinter import *
from tkinter import messagebox
def mainScreen():
Label(text="Please select an option.").pack()
Label(text="").pack()
Button(text="Login into an existing account.", command=login).pack()
Label(text="").pack()
Button(text="Create a new account.").pack()
def login():
loginScreen = Toplevel(root)
loginScreen.geometry("200x150")
loginScreen.title("Existing Account Login")
Label(loginScreen, text="Please enter your username.").pack()
Entry(loginScreen, textvariable=eUserName).pack()
Label(loginScreen, text="Please enter your password.").pack()
Entry(loginScreen, textvariable=ePassWord).pack()
Label(text="").pack()
Button(loginScreen, text="Click to login.", command=authenticate_name).pack()
def authenticate_name():
with open("usernames.txt") as file:
for username in file:
if eUserName.get() == username.strip():
authenticate_password()
return
messagebox.showerror("Invalid Username!", "This username is invalid!")
exit()
def authenticate_password():
with open("passwords.txt") as file:
for password in file:
if ePassWord.get() == password.strip():
game()
return
messagebox.showerror("Invalid Password!", "This password is incorrect!")
exit()
def game():
messagebox.showinfo("You're In!", "The game has begun!")
root = Tk()
root.geometry("250x175")
root.title("Login Screen")
eUserName = StringVar()
ePassWord = StringVar()
mainScreen()
root.mainloop()
My program creates a simple application, using Tkinter, that aims to compare a user's details (username and password) to a file.
My program uses 3 frames.
-"usernameFrame"
-"passwordFrame"
-"resultFrame"
It has a username label calld "ulab" and a password label called "plab"
It has an "Output" label which tells the user if he has successfully logged in or not
At the bottom it has a Login button which connects to the command "LoginF".
However, I always get the error "TypeError: LoginF() missing 2 required positional arguments: 'username' and 'password"
from tkinter import *
root = Tk()
root.title("Validating user details")
Title = Label(root,text="Welcome, please login below", fg = "blue", bg = "yellow", font = "Verdana 30 bold", bd=1, relief="solid",padx=20)
Title.pack(side = TOP)
usernameFrame = Frame(root)
usernameFrame.pack(side = TOP)
uLab = Label(usernameFrame,text="Enter username: ",fg="light green",bg="green",font = "Calibri 26 italic",bd=1, relief="solid")
uLab.pack(side = LEFT)
username = Entry(usernameFrame)
username.pack(side = LEFT)
passwordFrame = Frame(root)
passwordFrame.pack(side = TOP)
pnLab = Label(passwordFrame,text="Enter password: ",fg="light green",bg="green",font = "Calibri 26 italic",bd=1, relief="solid")
pnLab.pack(side = LEFT,fill = X,expand = 1)
password = Entry(passwordFrame,show="*")
password.pack(side = LEFT)
resultFrame = Frame(root)
resultFrame.pack(side = TOP)
Output = Label(resultFrame,text="Display Result Here",fg="#008080",bg="#00FFFF",font = "Tahoma 30 bold",bd=1, relief="solid")
Output.pack(side = LEFT,fill = X,expand = 1)
def LoginF(username,password):
Login = False
file = open("OCR PPP Python Login List_user.txt","r")
data = file.read()
if username+","+password in data:
Output.configure(text="Successfully logged in")
Login = True
else:
Output.configure(text="Hmm.. Try again")
Login = False
file.close()
logButton = Button(resultFrame,text="Login",fg="#FF8C00",bg="#FF4500",font = "Ariel 28 underline",bd=1, relief="solid",command=LoginF)
logButton.pack(side = LEFT)
root.mainloop()
This is because you haven't pass any arguments to the LoginF(...) function.
Either you do this:
logButton = Button(resultFrame,text="Login",fg="#FF8C00",bg="#FF4500",font = "Ariel 28 underline",bd=1, relief="solid",
command=lambda: LoginF(username.get(), password.get()))
To know more about how to pass functions as callback in tkinter.
Or
Change your LoginF() a little bit like so.
def LoginF():
username = username.get()
password = password.get()
Login = False
file = open("OCR PPP Python Login List_user.txt","r")
data = file.read()
if username+","+password in data:
Output.configure(text="Successfully logged in")
Login = True
else:
Output.configure(text="Hmm.. Try again")
Login = False
file.close()