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)
Related
from tkinter import *
from database import *
def Control_():
var1 = NameE.get()
var2 = LastnameE.get()
var3 = UsernameE.get()
var4 = PasswordE.get()
search = KullaniciAra(var3)
if search == None:
kullanici_ekle(var1,var2,var3,var4)
Login_Page()
else:
ErrorLabel = Label(win,text="This username is taken.")
ErrorLabel.grid(row=8,column=1)
def Login_Page():
def on_login():
var3 = UsernameE2.get()
var4 = PasswordE2.get()
search2 = KullaniciAra(var3)
if search2 == var4:
print("Done!")
win.destroy()
new_win = Tk()
new_win.title("T Messenger L")
new_win.geometry("200x200")
UsernameL2 = Label(new_win,text="Username",fg="black",bg="lightgray")
UsernameL2.grid(row=0,column=0)
UsernameE2 = Entry()
UsernameE2.grid(row=0,column=1)
PasswordL2 = Label(new_win,text="Password",fg="black",bg="lightgray")
PasswordL2.grid(row=1,column=0)
PasswordE2 = Entry()
PasswordE2.grid(row=1,column=1)
Button2 = Button(new_win,text="Login",command=on_login)
Button2.grid(row=2,column=1)
new_win.mainloop()
Tablo_olustur()
win = Tk()
win.title("T Messenger R")
win.geometry("200x200")
NameL = Label(win,text="Name",fg="black",bg="lightgray")
NameL.grid(row=1,column=0)
NameE = Entry()
NameE.grid(row=1,column=1)
LastnameL = Label(win,text="Lastname",fg="black",bg="lightgray")
LastnameL.grid(row=2,column=0)
LastnameE = Entry()
LastnameE.grid(row=2,column=1)
UsernameL = Label(win,text="Username",fg="black",bg="lightgray")
UsernameL.grid(row=3,column=0)
UsernameE = Entry()
UsernameE.grid(row=3,column=1)
PasswordL = Label(win,text="Password",fg="black",bg="lightgray")
PasswordL.grid(row=4,column=0)
PasswordE = Entry()
PasswordE.grid(row=4,column=1)
theLabel = Label(win,text="Login here",fg="blue",cursor="hand2",font=("TkDefaultFont",12,"underline"))
theLabel.grid(row=5,column=1)
theLabel.bind("<Button-1>", lambda event: Login_Page())
Button1 = Button(win,text="Register",command=Control_)
Button1.grid(row=6,column=1)
win.mainloop()
I wanted to make "login here" text with .bind() it worked as I want, it opened Login_Page() then even If I enter correct username and password when I click "Login" button nothing happens. What I want is "When 'login' button clicked and if username and password on my database and true open new page" and the new page name will be Vote_Page() cause user will choose like Find user, Update password, Delete acc etc
When writing a dialog box, you should use a Toplevel window as its base, not Tk. There should onle be one Tk instance in your program.
The implementation of FileDialog in cpython/filedialog.py is a nice example of how to implement a dialog in a class.
I am trying to make this app real quick for fun but when I try using a specific if statement, it doesn't follow through. Even though the values needed for it is present.
Here is the code for logging in and etc:
from tkinter import *
import json, threading, time
window = Tk()
window.title("MikuOS")
window.geometry('350x200')
global loggedin
loggedin = False
a = ''
if 'false' not in open('users.json', 'r').read():
lbl = Label(window, text="Welcome to MikuOS! MikuOS is in alpha.\nPlease enter a new password: ")
lbl.grid(column=0, row=0)
txt = Entry(window,width=15)
txt.grid(column=1, row=0)
def clicked():
json.dump({'users':{'password':txt.get(), 'firsttime':False}}, open('users.json', 'w'))
lbl.destroy()
txt.destroy()
btn.destroy()
btn = Button(window, text="entr", command=clicked)
btn.grid(column=2, row=0)
elif 'false' in open('users.json', 'r').read() and loggedin != True:
lbl = Label(window, text="Welcome to mikuOS!\nPlease enter your password to continue. ")
lbl.grid(column=0, row=0)
def clicked():
if txt.get() == json.load(open('users.json', 'r'))['users']['password']:
loggedin = True
lbl.destroy()
txt.destroy()
btn.destroy()
print(loggedin)
txt = Entry(window,width=15)
txt.grid(column=1, row=0)
btn = Button(window, text='enter', command=clicked)
btn.grid(column=1, row=1)
print(loggedin)
if loggedin == True:
print(loggedin)
def key_pressedo(event):
global a
a += 'o'
def olbld():
olbl.destroy()
if 'owo' in a:
a =''
olbl = Label(window, text="OwO mode activated! (it only displays this)")
olbl.grid(column=0,row=0)
olbl.after(5000, olbld)
print(a)
def key_pressedw(event):
global a
a+='w'
print(a)
window.bind("o",key_pressedo)
window.bind("w",key_pressedw)
window.mainloop()
No errors.
Here is some totally extra details in order for me to add the whole code so people can actually help me because stackoverflow is just annoying when it comes to preventing people from doing that but alright I understand why anyways this should be the end of this bye bye anyways I hope you can help me/get helped by this question.
The code is going back to loggedin = False constantly which causes it to reset to False and not keep it all True, you can fix this by putting the loggedin = False before the imports.
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()) "
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()
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")