I am having trouble getting these checks to work. it is for a password change program using tkinter. The aim is to make sure the password has both capital and lowercase letters, and is more than 8 characters long. the code always outputs false, even when the password should pass all the checks.
def check_password():
global oldpassword_entry
oldpasswordcheck= oldpassword_entry.get()
global newpassword_entry
newpasswordcheck= newpassword_entry.get()
global newpasswordconfirmed_entry
newpasswordconfirmedcheck= newpasswordconfirmed_entry.get()
if oldpasswordcheck == oldpassword:
if (any(x.isupper() for x in newpasswordcheck) and any(x.islower() for x in newpasswordcheck) and any(x.isdigit() for x in newpasswordcheck) and len(s) >= 8):
if newpasswordcheck == newpasswordconfirmedcheck:
passwordtrue = 'true'
print(passwordtrue)
showoldpasswordchange_label.configure(text=newpasswordconfirmedcheck)
else:
passwordtrue = 'false'
print(passwordtrue)
else:
passwordtrue = 'false'
print(passwordtrue)
else:
passwordtrue = 'false'
print(passwordtrue)
okaybutton_button = ttk.Button(root, text= "Okay", width= 20, command= check_password)
the variables at the start of the function come from the entries here:
showoldpassword_label = tk.Label(root, text = 'Current Password: ', font=('calibre',10, 'bold'))
showoldpasswordchange_label = tk.Label(root, text = 'PasswordExample', font=('calibre',10, 'bold'))
oldpassword_label = tk.Label(root, text = 'Old Password: ', font=('calibre',10, 'bold'))
oldpassword_entry = tk.Entry(root, font=('calibre',10,'normal'), show = '*')
newpassword_label = tk.Label(root, text = 'New Password: ', font=('calibre',10, 'bold'))
newpassword_entry = tk.Entry(root, font=('calibre',10,'normal'), show = '*')
newpasswordconfirmed_label = tk.Label(root, text = 'Confirm Password: ', font=('calibre',10, 'bold'))
newpasswordconfirmed_entry = tk.Entry(root, font=('calibre',10,'normal'), show = '*')
when the code is run it makes this box:
What is s in if (any(x.isupper() for x in newpasswordcheck) and any(x.islower() for x in newpasswordcheck) and any(x.isdigit() for x in newpasswordcheck) and len(s) >= 8):
Maybe just swap s for newpasswordcheck?
The code otherwise looks right to me, i havn't tried it though just read it and im missing s and oldpassword which i'm guessing is the current password as a string?
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 have a Python file that when run, opens a window for simple addition practice. It asks the user for their input, and if the total is correct will output "Right!" and "Oops!" for incorrect. Below all of this is a counter that keeps track of the correct number out of the total. However, at the moment, those numbers both remain zero when user enters their input. What kind of changes would need to be made under the ClicktheButton1 function in order to get this program properly functioning? Thanks.
The output would end up looking like "2 out 4 correct" in the window, updating after each new problem is solved.
from tkinter import *
import random as rn
window = Tk()
window.geometry('350x350')
window.title("C200")
x = rn.randint(0,100)
y = rn.randint(0,100)
correct, incorrect = 0,0
myLabel = Label(window, text="{0}+{1}=".format(x,y), font=("Arial Bold", 15))
myLabel.grid(column=0, row=0)
myLable2 = Label(window, text = "",font=("Arial Bold", 15))
myLable2.grid(column=0, row=5)
mylabel3 = Label(window,text = "0 out of 0 correct",font=("Arial Bold", 15))
mylabel3.grid(column=0, row=10)
mytxt = Entry(window, width=12)
mytxt.grid(column=1,row=0)
def ClicktheButton1():
global x
global y
global correct
global incorrect
myguess = int(mytxt.get())
if x + y == myguess:
myLable2.configure(text = "Right!")
correct += 1
else:
myLable2.configure(text = "Oops!")
incorrect += 1
x = rn.randint(0,100)
y = rn.randint(0,100)
mytxt.focus()
mytxt.delete(0,END)
myLabel.configure(text = "{0}+{1}=".format(x,y))
btn1 = Button(window, text="check", command = ClicktheButton1)
btn1.grid(column=0, row=7)
def ClicktheButton2():
window.destroy()
btn1 = Button(window, text="Quit", command = ClicktheButton2)
btn1.grid(column=400, row=400)
window.mainloop()
You have to change text in mylabel3 in the same why as you change text in myLabel - and even in the same place. I don't know why you have problem with this.
myLabel.configure(text = "{0}+{1}=".format(x,y))
mylabel3.configure(text="{0} of {1} correct".format(correct, correct+incorrect))
I am trying to create a standard user ID/PASS login. When I use the next function to check if the entered password and name are right, I always get the "wrong values entered" message. Basically, the variables entry_1 and entry_2 are not storing the input text and I want a solution for that. Maybe any of you guys might propose a solution for that?
I have tried to assign entry_1 and entry_2 to variables but it did'nt work out.
from tkinter import *
root = Tk() # creates a window and initializes the interpreter
root.geometry("500x300")
name = Label(root, text = "Name")
password = Label(root, text = "Password")
entry_1 = Entry(root)
entry_2 = Entry(root)
name.grid(row = 0, column = 0, sticky = E) # for name to be at right use sticky = E (E means east)
entry_1.grid(row = 0, column =1)
x = "Taha"
password.grid(row = 1, column = 0)
entry_2.grid(row = 1, column =1)
y = "123"
c = Checkbutton(root, text = "Keep in logged in").grid(columnspan = 2 ) # mergers the two columns
def next():
if a == entry_1 and b == entry_2:
print ("Proceed")
else:
print("wrong values entered")
def getname():
return name
Next = Button(root, text = "Next", command=next).grid(row = 3, column = 1)
root.mainloop() # keep runing the code
I want the program to return "Proceed" once correct values are entered.
in your code you're not checking for the user input anywhere. You should use get() to return user input. I've modified your code accordingly. Now if you enter Taha as username and 123 as password, you'll get the "Proceed" message.
from tkinter import *
root = Tk() # creates a window and initializes the interpreter
root.geometry("500x300")
name = Label(root, text="Name")
password = Label(root, text="Password")
entry_1 = Entry(root)
entry_2 = Entry(root)
name.grid(row=0, column=0, sticky=E) # for name to be at right use sticky = E (E means east)
entry_1.grid(row=0, column=1)
x = "Taha"
password.grid(row=1, column=0)
entry_2.grid(row=1, column=1)
y = "123"
c = Checkbutton(root, text="Keep in logged in").grid(columnspan=2) # mergers the two columns
def next_window():
user_name = entry_1.get()
user_pass = entry_2.get()
if x == user_name and y == user_pass:
print("Proceed")
else:
print("wrong values entered")
def get_name():
return name
Next = Button(root, text="Next", command=next_window).grid(row=3, column=1)
root.mainloop()
thanks to the people who helped, with your help i could find the missing part in the code. i should have used .get() funtion in order to get the entered text back.
here is the upgraded code with some improvements.
from tkinter import *
from tkinter import messagebox
root = Tk() # creates a window and initializes the interpreter
root.geometry("500x300")
name = Label(root, text = "Name")
password = Label(root, text = "Password")
entry_1 = Entry(root)
entry_2 = Entry(root)
name.grid(row = 0, column = 0, sticky = E) # for name to be at right use sticky = E (E means east)
entry_1.grid(row = 0, column =1)
x = "Taha"
password.grid(row = 1, column = 0)
entry_2.grid(row = 1, column =1)
y = "123"
c = Checkbutton(root, text = "Keep in logged in").grid(columnspan = 2 ) # mergers the two columns
def next():
a = entry_1.get()
b = entry_2.get()
if a == "Taha" and b =="123":
messagebox.showinfo("Login", "successfuly logged in ")
root.destroy()
print ("Proceed")
else:
messagebox.showerror("Error", "wrong values entered")
print("wrong values entered")
root.destroy()
Next = Button(root, text = "Next", command=next).grid(row = 3, column = 1)
root.mainloop() # keep runing the code
I am new in python and trying to make a program for converting a given string into a secret code. The string entered by user in the text box is taken as input and converted in secret code (using the encryption module). How do I display the result in the window (I tried using the label but it shows an error.)
from tkinter import *
import encryption as En # Loading Custom libraries
import decryption as De
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_box = None
resut_l = None
result_2 = None
def b1_action(): # Encryption button
input_text = text_box.get()
if input_text == "":
print("Text field empty")
else:
En.enc_text(input_text) # Message is returned as 'code'
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
De.dec_text(input_text)
def enc_button(): # Button for rendering encryption
b1 = Button(root, text = "ENCRYPT", font = button1_font, command = b1_action)
b1.configure(bg = 'palegreen3', width = '10', height = '3')
b1.place(x = '120', y = '130')
def dec_button(): # Button for decryption
b2 = Button(root, text = "DECRYPT", font = button2_font, command = b2_action)
b2.configure(bg = 'palegreen3', width = '10', height = '3')
b2.place(x = '340', y = '130')
def main(): #This is the core of GUI
global root
global text_box
root = Tk()
root.geometry("550x350")
root.configure(bg = "MediumPurple1")
win_text = Label(root, text = 'Enter text below and Choose an action:', bg = 'MediumPurple1', font = font_L1)
win_text.place(x = '10', y = '50')
text_box = Entry(root, text = 'Enter the Text', width = 60, bg = 'light blue')
text_box.place(x = '100', y = '100')
inst_text = Label(root, text = instructions, bg = "MediumPurple1", font = font_inst)
inst_text.pack(side = BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()
And here is the encryption module
def enc_text(line):
msg = str(line).replace(' ', '_').lower()
msg_list = list(msg)
all_char = list("abcdefghijklmnopqrstuvwxyzabc_!?#")
for i in range(0, len(msg)):
pos_replaced = all_char.index(str(msg_list[i])) #will give the positon of the word to be replaced in the main list of alphabets
msg_list.insert(i, all_char[pos_replaced + 3]) #will replace the elements one by one
msg_list.pop(i + 1)
i += 1
code = ''.join(msg_list).replace('#', ' ')
print(code)
You can also suggest some improvisations.
Part of the problem is that Entry widgets don't have a text= configuration option, so it's completely ignored in the line:
text_box = Entry(root, text='Enter the Text', width=60, bg='light blue')
The best way to handle the character contents of an Entry is by using its textvariable= option and setting the value of it to be an instance of a tkinter.StringVar, then the getting and setting the value of that object will automatically update the Entry widget on the screen.
Below is your code with changes made to it to do this. Note I commented and changed a few unrelated things to be able to run the code, but tried to indicate the most important ones. Also note I added a return code statement at the very end of the enc_text() function in your custom encryption module.
from tkinter import *
import encryption as En # Loading Custom libraries
#import decryption as De # DON'T HAVE THIS.
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_var = None # ADDED.
text_box = None
resut_l = None
result_2 = None
# CHANGED TO USE NEW "text_var" variable.
def b1_action(): # Encryption button
input_text = text_var.get()
if input_text == "":
print("Text field empty")
else:
text_var.set(En.enc_text(input_text))
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
"""De.dec_text(input_text)"""
def enc_button(): # Button for rendering encryption
b1 = Button(root, text="ENCRYPT", font=button1_font, command=b1_action)
b1.configure(bg='palegreen3', width='10', height='3')
b1.place(x='120', y='130')
def dec_button(): # Button for decryption
b2 = Button(root, text="DECRYPT", font=button2_font, command=b2_action)
b2.configure(bg='palegreen3', width='10', height='3')
b2.place(x='340', y='130')
def main(): #This is the core of GUI
global root
global text_box
global text_var # ADDED
root = Tk()
root.geometry("550x350")
root.configure(bg="MediumPurple1")
win_text = Label(root, text='Enter text below and Choose an action:',
bg='MediumPurple1', font=font_L1)
win_text.place(x='10', y='50')
text_var = StringVar() # ADDED
text_var.set('Enter the Text') # ADDED
# CHANGED text='Enter the Text' to textvariable=text_var
text_box = Entry(root, textvariable=text_var, width=60, bg='light blue')
text_box.place(x='100', y='100')
inst_text = Label(root, text="instructions", bg="MediumPurple1",
font=font_inst)
inst_text.pack(side=BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()
I'm trying to build a gui that creates a password and i've got as far as generating the password and making it appear in a label. However when the button is clicked multiple times it appears the old password doesnt dissapear, it just overlays on top. I'm also getting an error that i cant seem to rectify, although it doesnt seem to affect the gui.
The code so far is:
from tkinter import *
import random
myGui = Tk()
myGui.geometry('300x200+700+250')
myGui.title('Password Generator')
def passwordgen():
password = ''
for i in range(8):
##----runs the for loop 8 times
if (i == 0) or (i == 4):
password = password + chr(random.randint(97, 122))
if (i == 1) or (i == 5):
password = password + chr(random.randint(65, 90))
if (i == 2) or (i == 6):
password = password + chr(random.randint(48, 57))
if (i == 3) or (i == 7):
password = password + chr(random.randint(33, 47))
passLabel = Label(myGui, text=password)
passLabel.grid(row=0, column=1, sticky=E)
genPassBtn = Button(myGui, text="Generate Password", command=passwordgen)
genPassBtn.bind("<Button-1>", passwordgen)
genPassBtn.grid(row=0, column=0, sticky=W)
myGui.mainloop()
The error i receive is:
return self.func(*args)
TypeError: passwordgen() takes 0 positional arguments but 1 was given
The outcome i am hoping to achieve is to create a gui that generates a password, generates a hash value for generated password, checks the password strength, loads the generated hash to a text file and then can verify the password against stored hashes.
Further on now and from advice received i have amended the code and added extra to check the strength. The code now looks like this:
from tkinter import *
import random
myGui = Tk()
myGui.geometry('300x200+700+250')
myGui.title('Password Generator')
def passwordgen():
password = ''
for i in range(8):
##----runs the for loop 8 times
if (i == 0) or (i == 4):
password = password + chr(random.randint(97, 122))
if (i == 1) or (i == 5):
password = password + chr(random.randint(65, 90))
if (i == 2) or (i == 6):
password = password + chr(random.randint(48, 57))
if (i == 3) or (i == 7):
password = password + chr(random.randint(33, 47))
strPassword.set(password)
def checkPassword():
strength = ['Blank', 'Very Weak', 'Weak', 'Medium', 'Strong', 'Very Strong']
score = 1
password = strPassword.get()
if len(password) < 1:
return strength[0]
if len(password) < 4:
return strength[1]
if len(password) >= 8:
score += 1
if re.search('[0-9]', password):
score += 1
if re.search('[a-z]', password) and re.search('[A-Z]', password):
score += 1
if re.search('.', password):
score += 1
passwordStrength.set(strength[score])
genPassBtn = Button(myGui, text="Generate Password", command=passwordgen)
strPassword = StringVar()
lblPassword = Label(myGui, textvariable=strPassword)
lblPassword.grid(row=0, column=1, sticky=W)
genPassBtn.grid(row=0, column=0, sticky=W)
passwordStrength = StringVar()
checkStrBtn = Button(myGui, text="Check Strength", command=checkPassword)
checkStrBtn.grid(row=1, column=0)
checkStrLab = Label(myGui, textvariable=passwordStrength)
checkStrLab.grid(row=1, column=1)
myGui.mainloop()
Try this example.
from tkinter import *
import random
myGui = Tk()
myGui.geometry('300x200+700+250')
myGui.title('Password Generator')
def passwordgen():
password = ''
for i in range(8):
##----runs the for loop 8 times
if (i == 0) or (i == 4):
password = password + chr(random.randint(97, 122))
if (i == 1) or (i == 5):
password = password + chr(random.randint(65, 90))
if (i == 2) or (i == 6):
password = password + chr(random.randint(48, 57))
if (i == 3) or (i == 7):
password = password + chr(random.randint(33, 47))
strPassword.set(password)
genPassBtn = Button(myGui, text="Generate Password", command=passwordgen)
strPassword = StringVar()
lblPassword = Label(myGui, textvariable=strPassword)
lblPassword.grid(row=0,column=1, sticky=W)
genPassBtn.grid(row=0, column=0, sticky=W)
myGui.mainloop()
Here's what I've done
Rather than creating a new label each time, I change the text of a label using the StringVar called strPassword.
You don't need to bind a button to a click to call a function, using Button(... , command=myFunction) does this already.