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 1 year ago.
The goal of this code is to create a functioning login screen. However, in the process of creating the "create_account()" and implementing it, I noticed that for some reason it triggers as soon as the program runs. Not only that but when the button that the function is linked to is clicked, nothing seems to happen. What gives?
from tkinter import *
counter = 0
def login():
user = txt.get()
pwd = txt2.get()
if user in users:
if pwd == users[user]:
lbl3.config(text="Login successful")
else:
lbl3.config(text="Invalid username or password")
else:
lbl3.config(text="Invalid username or password")
user = txt.get()
pwd = txt2.get()
certificate = 0
if user in users:
if pwd == users[user]:
lbl3.config(text="Login successful")
else:
lbl3.config(text="Invalid username or password")
else:
lbl3.config(text="Invalid username or password")
def up(string):
for x in string:
if(x.upper()):
return True
else:
return False
def low(string):
for x in string:
if(x.lower()):
return True
else:
return False
def length(string):
if(len(string) > 8 and len(string) < 15):
return True
else:
return False
def whitespace(string):
for x in string:
if(x.isspace()):
return False
else:
return True
def number(string):
for x in string:
if(x.isdigit()):
return True
else:
return False
def alphanumberic(string):
for x in string:
if(x.isalnum()):
return False
else:
return True
def valid_password(string):
up(string)
low(string)
length(string)
whitespace(string)
number(string)
alphanumberic(string)
if(string==("BigCodez4life!")):
return True
def valid_username(string):
up(string)
low(string)
whitespace(string)
number(string)
alphanumberic(string)
if(string==("BigCodez4life!")):
return True
if(length(string) == True and whitespace(string) == False and number(string) == True and alphanumberic(string) == False and up(string) == True and low(string) == True):
return True
else:
return False
def create_account():
username = txt.get()
password = txt2.get()
if username != "" and valid_username(username) == True and valid_password(password) == True:
lbl3.config(text="Account Created")
else:
lbl3.config(text="Invalid username or password")
window = Tk()
window.title("Login Window")
window.geometry("480x270")
lbl = Label(window, text="Username")
lbl.grid(column=0, row=0)
lbl2 = Label(window, text="Password")
lbl2.grid(column=0, row=1)
lbl3 = Label(window, text="Hidden")
lbl3.grid(column=1, row=10)
lbl3['foreground']="red"
lbl3['width']=30
txt = Entry(window,width=15)
txt.grid(column=1, row=0)
txt2 = Entry(window,width=15,show="*")
txt2.grid(column=1, row=1)
btn = Button(window, text="Login", command=login)
btn.grid(column=2, row=7)
btn2 = Button(window, text="Create Account", command=create_account())
btn2.grid(column=0, row=7)
users = dict()
realusers = []
pwds = []
window.mainloop()
It is because of this line:
btn2 = Button(window, text="Create Account", command=create_account())
command=create_account will run create_account once the line is executed. All you need to do is remove the parenthesis and most likely it will work just fine.
Related
I created a password generator, which creates random passwords out of symbols, numbers and characters. There I have an input, where the user must enter a value and it has to be numeric. So I tried to solve this with elif. But, even when expected number (int) is entered, the loop is still stuck at elif. Here my code:
def PasswordGenerationFunc():
password = None
passwordLength = inputPasswordLength.get()
userName = inputUsername.get()
if len(passwordLength) == 0:
ResultDisplay.configure(text="Length of password is mandatory.", fg="red")
elif type(passwordLength) != int:
ResultDisplay.configure(text="Only digits are allowed." + passwordLength, fg="red")
else:
passwordLength = int(passwordLength)
if passwordLength > maxPasswordLength:
ResultDisplay.configure(text="The limit of password length are 20 characters.", fg="red")
else:
if userName != "":
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password for " + userName + " is:\n" + password, fg="white")
else:
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password is: \n" + password, fg="white")
In
ResultDisplay.configure(text="Only digits are allowed." + passwordLength, fg="red")
I print out passwordLength to check if wrong values were passed, but was not the case. I am so into the loop, I might ignoring some logic.
Expected behaviour:
User enters letters, loop stops at elif. User enters digits, loop enters else condition.
Now:
User enters digits, loop still stops at elif.
Here my full code, so you might understand it better:
# This is a small tool to generate passwords
# IMPORTS
from datetime import datetime
import random
from tkinter import *
# VARIABLES
date = datetime.now()
dateFormat = str(date.strftime("%d-%m-%Y %H:%M:%S"))
lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "!?%&##+*"
passwordConstructor = lowerCase + upperCase + numbers + symbols
maxPasswordLength: int = 20
bgColor_1 = "black"
# MAKE OUTPUT SELECTABLE
# GENERATE PASSWORD FUNCTION
def PasswordGenerationFunc():
password = None
passwordLength = inputPasswordLength.get()
userName = inputUsername.get()
if len(passwordLength) == 0:
ResultDisplay.configure(text="Length of password is mandatory.", fg="red")
#elif type(passwordLength) != int:
elif isinstance(passwordLength, int):
ResultDisplay.configure(text="Only digits are allowed.", fg="red")
else:
passwordLength = int(passwordLength)
if passwordLength > maxPasswordLength:
ResultDisplay.configure(text="The limit of password length are 20 characters.", fg="red")
else:
if userName != "":
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password for " + userName + " is:\n" + password, fg="white")
else:
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password is: \n" + password, fg="white")
# SCREEN
screen = Tk()
screen.geometry("450x400")
screen.configure(bg="black")
screen.title("PASSWORD GENERATOR")
# TITLE
Title = Label(screen, text="PASSWORD GENERATOR", font=("Arial Bold", 18), fg="green")
Title.configure(bg="black")
Title.pack(pady=20)
# MAIN FRAME
MainFrame = Frame(screen)
MainFrame.configure(bg="black")
MainFrame.pack(pady=5)
# INPUT USERNAME
usernameLabel = Label(MainFrame, text="Please enter username:", font=("Arial Bold", 14))
usernameLabel.configure(bg="black")
usernameLabel.pack()
inputUsername = Entry(MainFrame, font=("Arial Bold", 12))
inputUsername.pack()
# INPUT PASSWORD LENGTH
passwordLengthLabel = Label(MainFrame, text="Please enter length of password:", font=("Arial Bold", 14))
passwordLengthLabel.configure(bg="black")
passwordLengthLabel.pack()
inputPasswordLength = Entry(MainFrame, font=("Arial Bold", 12))
inputPasswordLength.pack()
# GENERATE BUTTON
GenerateBtn = Button(MainFrame, text="GENERATE", font=("Arial", 14), command=PasswordGenerationFunc, bg="black")
GenerateBtn.pack(pady=10)
# DISPLAY RESULT
ResultDisplay = Label(MainFrame, text="", font=("Arial", 14))
ResultDisplay.configure(bg="black")
ResultDisplay.pack(pady=15)
# COPY TO CLIPBOARD BUTTON
#CopyBtn = Button(MainFrame, text="COPY", font=("Arial", 14), bg="black")
#CopyBtn.clipboard_append(password)
#CopyBtn.pack(pady=10)
# WINDOW
screen.mainloop()
First, convert the input to int.
try:
passwordLength = int(input("Your message "))
except ValueError:
print(f"Input is not a valid integer. Please try again.")
Modify the if conditions for an integer input as follows:
if passwordLength == 0:
pass # your output here
else:
pass # your logic to generate a password
To compare objects and its datatype use isinstance(object, type):
isinstance(3, int) ===> True
isinstance(3, str) ===> False
I am trying to build a python application. The first UGI is requesting the username and password. Then a second tk window pops up if login is successful with an okay button. Once then user press the okay button, both tk windows (the one requesting username and password and the login successful msg window) will disappear and the program continues to run.
I am very stuck with being able to press the okay button and close "both" windows. Any insights will be appreciated, thank you!
All the codes seem to be working fine. the command to execute function LoginSuccessful within the CheckLogin is able to execute the print("ANCD") but it doesn't close the two tk windows.
#import packages
import time
import openpyxl
from openpyxl import load_workbook
import tkinter as tk
from tkinter import *
import sys
def Function():
global user1
user1 = 'testing'
password1 = '0000'
def Login_form():
global username
global password
global rootA
rootA = Tk()
rootA.title('User Authentication')
msgbox1 = Label(rootA, text='Please Login\n')
msgbox1.grid(sticky=E)
username = Label(rootA, text='Username: ')
password = Label(rootA, text='Password: ')
username.grid(row=1, sticky=W)
password.grid(row=2, sticky=W)
username = Entry(rootA)
password = Entry(rootA, show='*')
username.grid(row=1, column=1)
password.grid(row=2, column=1)
login_btn = Button(rootA, text='Login', command=CheckLogin)
exit_btn=Button(rootA, text='Exit',command=sys.exit)
login_btn.grid(row=4, column=1)
exit_btn.grid(row=4, column=2)
rootA.mainloop()
def CheckLogin():
if username.get() == user1 and password.get() == password1:
rootA = Tk()
rootA.title('Authentication Cehck')
rootA.geometry('150x100') # Makes the window a certain size
rlbl = Label(rootA, text='\n Logged In')
okay_btn=Button(rootA, text='Okay',command=LoginSuccessful)
okay_btn.pack()
#LoginSuccessful()
else:
r = Tk()
r.title('Authentication Cehck')
r.geometry('150x160')
rlbl = Label(r, text='\n Invalid Login')
rlbl.pack()
okay_btn=Button(r, text='Try Again',command=r.destroy)
okay_btn.pack()
exit_btn=Button(r, text='Exit',command=sys.exit)
exit_btn.pack()
#r.mainloop()
def LoginSuccessful ():
rootA.destroy
print("ANCD")
def Insert_Rows():
for rows in range (len(All_Users_Sheet)):
if rows == 0:
rows +1
continue
if All_Users_Sheet[rows][10].value == None:
break
else:
print(All_Users_Sheet[rows][10].value)
print(type(All_Users_Sheet[rows][10].value))
Login_form()
Function()
Is there any way that after checking the username and password, if it's correct, close all tk windows by pressing a button and continue running the remaining tasks?
You should only create one instance of Tk. If you needed additional window, use Toplevel instead.
def CheckLogin():
if username.get() == user1 and password.get() == password1:
rootA = Toplevel()
rootA.title('Authentication Check')
...
else:
r = Toplevel()
...
i got one solution.
from tkinter import *
global user1
user1 = 'testing'
password1 = '0000'
def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
def Login_form():
global username
global password
global rootA
rootA = Tk()
rootA.title('User Authentication')
msgbox1 = Label(rootA, text='Please Login\n')
msgbox1.grid(sticky=E)
username = Label(rootA, text='Username: ')
password = Label(rootA, text='Password: ')
username.grid(row=1, sticky=W)
password.grid(row=2, sticky=W)
username = Entry(rootA)
password = Entry(rootA, show='*')
username.grid(row=1, column=1)
password.grid(row=2, column=1)
login_btn = Button(rootA, text='Login', command=CheckLogin)
exit_btn=Button(rootA, text='Exit',command=rootA.destroy)
login_btn.grid(row=4, column=1)
exit_btn.grid(row=4, column=2)
rootA.mainloop()
def CheckLogin():
global rootA
if username.get() == user1 and password.get() == password1:
rootA = Tk()
rootA.title('Authentication Cehck')
rootA.geometry('150x100') # Makes the window a certain size
rlbl = Label(rootA, text='\n Logged In')
okay_btn=Button(rootA, text='Okay',command=LoginSuccessful)
okay_btn.pack()
#LoginSuccessful()
else:
r = Tk()
r.title('Authentication Cehck')
r.geometry('150x160')
rlbl = Label(r, text='\n Invalid Login')
rlbl.pack()
okay_btn=Button(r, text='Try Again',command=r.destroy)
okay_btn.pack()
exit_btn=Button(r, text='Exit',command= combine_funcs(rootA.destroy, r.destroy))
exit_btn.pack()
#r.mainloop()
def LoginSuccessful ():
rootA.destroy
print("ANCD")
def Insert_Rows():
for rows in range (len(All_Users_Sheet)):
if rows == 0:
rows +1
continue
if All_Users_Sheet[rows][10].value == None:
break
else:
print(All_Users_Sheet[rows][10].value)
print(type(All_Users_Sheet[rows][10].value))
Login_form()
please dont't ask about def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
,it just solves the problem
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()
I have a issue when I want to populate a entry box using tkinter. My current script are calling another script to get values. Then I want the data to be displayed in a Tkinter entry box.
This is my current code, I am have tried tbName.set("tbName", account.getName()) somethhing like that (with and without the tbName) I have also triws StringVar. I am not sure if I am using it wrong. I have looked at the following site : effbot. I am very new to Python so any help will b apritiated.
from Tkinter import *
from bank import Bank, SavingsAccount
class BankManager(object):
root = Tk()
lblName = Label(root, text="Name")
lblPin = Label(root, text="Pin")
lblBalance = Label(root, text="Balance R")
lblStatus = Label(root, text="Status")
tbName = Entry(root)
tbPin = Entry(root)
tbBalance = Entry(root)
tbStatus = Entry(root)
def __init__(self):
self.bank = None
self.app = None
self.current_index = 0
self.create_bank()
self.populate_gui(self.current_index)
def new_account(self, event):
name = self.app.getEntry('name')
pin = self.app.getEntry('pin')
balance = self.app.getEntry('balance')
account = self.bank.get(pin)
if account:
self.app.setEntry("status", "Account with pin exists")
else:
self.bank.add(SavingsAccount(name, pin, float(balance)))
self.app.setEntry("status", "New account created")
self.current_index = self.bank.getPins().index(pin)
btnNewAcc = Button(root,text="New Account")
btnNewAcc.bind("<Button>",new_account)
def update_account(self, event):
name = self.app.getEntry('name')
pin = self.app.getEntry('pin')
balance = self.app.getEntry('balance')
account = self.bank.get(pin)
if account:
account._name = name
account._balance = balance
self.app.setEntry("status", "Account updated")
else:
self.app.setEntry("status", "Account with pin doesn't exist")
btnUpdateAcc = Button(root, text="Update Account")
btnUpdateAcc.bind("<Button>",update_account)
def remove_account(self, event):
pin = self.app.getEntry('pin')
account = self.bank.get(pin)
if account:
self.bank.remove(pin)
self.app.setEntry("status", "Account removed")
self.current_index = 0
else:
self.app.setEntry("status", "Account with pin doesn't exist")
btnRemoveAcc = Button(root,text="Remove Account")
btnRemoveAcc.bind("<Button>",remove_account)
def compute_interest(self, event):
self.bank.computeInterest()
pin = self.app.getEntry('pin')
account = self.bank.get(pin)
if account:
self.app.setEntry("status", "Interest updated")
self.app.setEntry("balance", str(account.getBalance()))
else:
self.app.setEntry("status", "Account with pin doesn't exist")
btnConputeInterest = Button(root,text="Compute Interest")
btnConputeInterest.bind("<Button>",compute_interest)
def press_navigator(self, event):
if button == "Previous":
if self.current_index == 0:
self.current_index = len(self.bank.getPins()) - 1
else:
self.current_index -= 1
elif button == "Next":
if self.current_index == len(self.bank.getPins()) - 1:
self.current_index = 0
else:
self.current_index += 1
self.populate_gui(self.current_index)
btnPrevious = Button(root,text="Previous")
btnPrevious.bind("<Button>",press_navigator)
btnNext = Button(root,text="Next")
btnNext.bind("<Button>",press_navigator)
lblName.grid(row=0)
lblPin.grid(row=1)
lblBalance.grid(row=2)
lblStatus.grid(row=3)
tbName.grid(row=0, column=1)
tbPin.grid(row=1, column=1)
tbBalance.grid(row=2, column=1)
tbStatus.grid(row=3, column=1)
btnNewAcc.grid(row=0, column=2)
btnUpdateAcc.grid(row=1, column=2)
btnRemoveAcc.grid(row=2, column=2)
btnConputeInterest.grid(row=3, column=2)
btnPrevious.grid(row=4, column=0)
btnNext.grid(row=4, column=1)
root.mainloop()
def create_bank(self):
self.bank = Bank()
a1 = SavingsAccount('zzz', '111', 100)
a2 = SavingsAccount('yyy', '222', 200)
a3 = SavingsAccount('xxx', '333', 300)
self.bank.add(a1)
self.bank.add(a3)
self.bank.add(a2)
def populate_gui(self, index):
account = self.bank.get(self.bank.getPins()[index])
tbName.set("tbName", account.getName())
if __name__ == '__main__':
BankManager()
if you want to set text in the Entry widget, you need to use Entry.insert(0,'text') instead of v.set. The 0 in the insert method is the place you want to insert the text, in this case it is in the beginning of the Entry.
If you don't want the user to edit what is inside the Entry, you can use Entry.config(state='readonly'); if you want to edit the content later you need to call Entry.config(state=NORMAL) before you can use Entry.insert again. You don't need to set StringVar to the Entry, only using Entry.get() is sufficient.
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()