Python Forum
[Tkinter] password with Entry widget
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] password with Entry widget
#1
Hi

I tried to set a password with widget Entry,

The right password is "tarek"
Only 3 attempts are allowed

the goal is :
when i enter a wrong password this text will appear in comment area :
*before the 1er attempt no text will appear
*after the 1st wrong password entry : "Try again, remaining attempts :2"
*after the 2st wrong password entry : "Try again, remaining attempts :1"
*after the 3st wrong password entry : "Acces denied, out of try" and the program will exit

when i enter the correct password, this text will appear in comment area : "Congratulation, acces autorized" and an other file that i alled "program2.py" will automatically executed.

The issues with my code are :
-this message appears even after the 2nd or the 3rd wrong password entry : "Try again, remaining attempts :2"
-I dont know how to insert a command to exit after the 3rd wrong attempt
-I dont know how to insert a command to execute the other program "program2.py" when i enter the right password

I wonder if i have to use the "WHILE function" instead of the "if function" or to use an other widget or kind of event?

Please can you help me to correct my code .

(Sorry I couldnt use python tags )

My code is the following :



___________________________________________________
# -*- coding: utf-8 -*-

from tkinter import ttk, Entry
#import tkinter as tk
from tkinter import *
from tkinter import filedialog
import os
from PIL import Image, ImageTk
import sqlite3
import getpass
Profile = {1:""}

def authorization(event) :
    rightpassword="tarek"
    word = entrypassword.get()
    nb_attempt = 1
    attempt_limit = 3
    attempt_authorized = True
    if word != rightpassword :
        nb_attempt = nb_attempt+1
        if nb_attempt <= attempt_limit:
            attempt_authorized = True
            comments = ("Try again, remaining attempts : " + str(attempt_limit +1 - nb_attempt))
            entrycomment.delete(0, END)
            entrycomment.insert(0, comments)
            print(entrycomment.get())
        else :
            attempt_authorized = False
            comments = ("Access denied, out of try")
            entrycomment.delete(0, END)
            entrycomment.insert(0, comments)
            print(entrycomment.get())
            exit
    else:
        comments = "Congratulation Access authorized"
        entrycomment.delete(0, END)
        entrycomment.insert(0, comments)
        print(entrycomment.get())
        open("D:/program2.py")

root = Tk()
root.title("Access Application")
root.geometry("1400x480")
#root.configure(bg = "#eaeaea")

# Add Title1
lblTitle1 = Label(root , text = "Gestion des accès" , font = ("Arial" , 21) , bg="darkblue" , fg = "white" )
lblTitle1.place(x=50 , y=0 , width=300)

# password area
lbpassword = Label(root , text = "Password :"  , font = ("Arial" , 21), bg="darkblue" , fg = "white" )
lbpassword.place(x=450 , y=200 , width=300)
entrypassword = Entry(root, font = ("Arial" , 21))
entrypassword.bind("<Return>" , authorization)
entrypassword.place(x=780 , y=200 , width=300)

lbcomment = Label(root , text = "Comment :"  ,font = ("Arial" , 21), bg="black" , fg = "white" )
lbcomment.place(x=180 , y=250 , width=250)
entrycomment = Entry(root , font = ("Arial" , 21), bg="white" , fg = "red" )
entrycomment.place(x=450 , y=250 , width=800)



root.mainloop()
Reply
#2
The callback is called every time you hit <Return> due to the binding.

But the count isn't stored outside this function. Every time you call it, the attempt count is reset to 1 (line 16). You'd need to store the attempt count outside this function (in an enclosing class, an enclosing function, or as a global).
Reply
#3
ok, i undestand the issue but how to solve it, can you please propose a correct code

thank you in advance
Reply
#4
Hi

I tried to set a password with widget Entry,

The right password is "tarek"
Only 3 attempts are allowed

the goal is :
when i enter a wrong password this text will appear in comment area :
*before the 1er attempt no text will appear
*after the 1st wrong password entry : "Try again, remaining attempts :2"
*after the 2st wrong password entry : "Try again, remaining attempts :1"
*after the 3st wrong password entry : "Acces denied, out of try" and the program will exit

when i enter the correct password, this text will appear in comment area : "Congratulation, acces autorized" and an other file that i alled "program2.py" will automatically executed.

The issues with my code are :
-this message appears even after the 2nd or the 3rd wrong password entry : "Try again, remaining attempts :2"
-I dont know how to insert a command to exit after the 3rd wrong attempt
-I dont know how to insert a command to execute the other program "program2.py" when i enter the right password

I wonder if i have to use the "WHILE function" instead of the "if function" or to use an other widget or kind of event?

Please can you help me to correct my code . I am waiting your proposal



My code is the following :



___________________________________________________
# -*- coding: utf-8 -*-
 
from tkinter import ttk, Entry
#import tkinter as tk
from tkinter import *
from tkinter import filedialog
import os
from PIL import Image, ImageTk
import sqlite3
import getpass
Profile = {1:""}
 
def authorization(event) :
    rightpassword="tarek"
    word = entrypassword.get()
    nb_attempt = 1
    attempt_limit = 3
    attempt_authorized = True
    if word != rightpassword :
        nb_attempt = nb_attempt+1
        if nb_attempt <= attempt_limit:
            attempt_authorized = True
            comments = ("Try again, remaining attempts : " + str(attempt_limit +1 - nb_attempt))
            entrycomment.delete(0, END)
            entrycomment.insert(0, comments)
            print(entrycomment.get())
        else :
            attempt_authorized = False
            comments = ("Access denied, out of try")
            entrycomment.delete(0, END)
            entrycomment.insert(0, comments)
            print(entrycomment.get())
            exit
    else:
        comments = "Congratulation Access authorized"
        entrycomment.delete(0, END)
        entrycomment.insert(0, comments)
        print(entrycomment.get())
        open("D:/program2.py")
 
root = Tk()
root.title("Access Application")
root.geometry("1400x480")
#root.configure(bg = "#eaeaea")
 
# Add Title1
lblTitle1 = Label(root , text = "Gestion des accès" , font = ("Arial" , 21) , bg="darkblue" , fg = "white" )
lblTitle1.place(x=50 , y=0 , width=300)
 
# password area
lbpassword = Label(root , text = "Password :"  , font = ("Arial" , 21), bg="darkblue" , fg = "white" )
lbpassword.place(x=450 , y=200 , width=300)
entrypassword = Entry(root, font = ("Arial" , 21))
entrypassword.bind("<Return>" , authorization)
entrypassword.place(x=780 , y=200 , width=300)
 
lbcomment = Label(root , text = "Comment :"  ,font = ("Arial" , 21), bg="black" , fg = "white" )
lbcomment.place(x=180 , y=250 , width=250)
entrycomment = Entry(root , font = ("Arial" , 21), bg="white" , fg = "red" )
entrycomment.place(x=450 , y=250 , width=800)
 
 
 
root.mainloop()
Reply
#5
I soft-deleted the post you made 9 minutes ago. Please don't create multiple threads with the same post.
Reply
#6
If you don't know how to solve a problem like this you have a big hole in your understanding of Python variables and scope. You should do some reading because this same problem is going to keep reappearing in ever more devious ways until you understand what is going on. When I was first learning Python I found this useful:

https://www.geeksforgeeks.org/namespaces...in-python/

Variables defined inside a function exist in the function's scope (or namespace). These variables disappear once the function is done running. You cannot define the number of password tries inside your authorization function because each time authorization function is done running, the nb_attempt variable is forgotten (is deleted). You must define the nb_attempt variable somewhere else, in a scope/namespace that is not deleted.
Reply
#7
I tried several times but i could not.
If you can propose an adjustment of my code, i would be graceful.
Otherwise i will make the password with the input widget(this one i could make it running correctly).
thanks for your support.
Reply
#8
(Sep-22-2020, 01:56 PM)TAREKYANGUI Wrote: I tried several times but i could not.
If you can propose an adjustment of my code, i would be graceful.
Otherwise i will make the password with the input widget(this one i could make it running correctly).
thanks for your support.
Note, I've only been learning Python for around 2 weeks total but I can help show your problem in a simple way. Generally you want to avoid making a variable global and instead change the way in which you approach the password solving (as you mentioned a while loop for example) is probably far more sensible. I also tried to make it very simple to demonostrate the difference in variable scope as oppose to tackling your exact issue.

Essentially the people before were trying to point you in the right direction and even mention the line that is the issue and an explaination on why it's an issue. If you're unable to find the cause yourself, it's pretty much certain you'll face the same issue over and over again in the future and that is what everyone is trying to help you avoid.

def passs() :
    password = "Enter"
    guess = input("Enter password: ")
    nbattempt = 1
    attemptlimit = 3
    if guess != password :
        print("Try again, attempts remaining:", attemptlimit - nbattempt)
        nbattempt = nbattempt + 1
    return
passs()
passs()
If you run that your output will be the same, even if you enter the incorrect password twice.
You need to make the variables that your function is changing to be global, e.g. they will change the variable outside the scope of the function, rather than just changing the variable within the function itself.

Run both lots of code and see the difference.

def passs(attempt, limit) :
    global nbattempt
    global attemptlimit
    password = "Enter"
    guess = input("Enter password: ")
    if guess != password :
        limit = attemptlimit - nbattempt
        print("Try again, attempts remaining:", limit)
        nbattempt = nbattempt + 1
    return limit

nbattempt = 1
attemptlimit = 3
passs(nbattempt, attemptlimit)
passs(nbattempt, attemptlimit)
As I say this isn't me fixing your code but trying to show you how the scope of variables work and why your variable isn't changing even with repeat incorrect password attempts.
Reply
#9
Creating GUI code is easier if you use classes.
Here is an example of your code turned into a class.
import tkinter as tk


class Main:
    def __init__(self, root):
        self.root = root
        self.rightpassword = "tarek"
        self.nb_attempt = 0
        self.attempt_limit = 3
        self.attempt_authorized = True

        root.title("Access Application")
        root.geometry("1400x480")
        # root.configure(bg = "#eaeaea")

        # Add Title1
        lblTitle1 = tk.Label(root, text="Gestion des accès", font=(
            "Arial", 21), bg="darkblue", fg="white")
        lblTitle1.place(x=50, y=0, width=300)

        # password area
        lbpassword = tk.Label(root, text="Password :", font=(
            "Arial", 21), bg="darkblue", fg="white")
        lbpassword.place(x=450, y=200, width=300)
        entrypassword = tk.Entry(root, font=("Arial", 21))
        entrypassword.bind("<Return>", self.entrypassword_return_event)
        entrypassword.place(x=780, y=200, width=300)
        self.entrypassword = entrypassword

        lbcomment = tk.Label(root, text="Comment :", font=(
            "Arial", 21), bg="black", fg="white")
        lbcomment.place(x=180, y=250, width=250)
        entrycomment = tk.Entry(root, font=("Arial", 21), bg="white", fg="red")
        entrycomment.place(x=450, y=250, width=800)
        self.entrycomment = entrycomment

    def entrypassword_return_event(self, event):
        word = self.entrypassword.get()
        if word != self.rightpassword:
            self.authorization_attempt()
        else:
            self.update_entry_comment("Congratulation Access authorized")
            self.authorized_code()

    def authorization_attempt(self):
        self.nb_attempt += 1
        if self.nb_attempt < self.attempt_limit:
            self.attempt_authorized = True
            self.update_entry_comment((
                "Try again, remaining attempts : "
                f"{self.attempt_limit-self.nb_attempt}"))
        else:
            self.attempt_authorized = False
            self.update_entry_comment("Access denied, out of trys")
            self.root.after(3000, self.root.quit)

    def update_entry_comment(self, comment):
        self.entrycomment.delete(0, tk.END)
        self.entrycomment.insert(0, comment)

    def authorized_code(self):
        print('add authorized code here')


root = tk.Tk()
Main(root)
root.mainloop()
Reply
#10
Great, thanks for your support
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  ValueError: could not convert string to float: '' fron Entry Widget russellm44 5 490 Mar-06-2024, 08:42 PM
Last Post: russellm44
  [Tkinter] entry widget DPaul 5 1,427 Jul-28-2023, 02:31 PM
Last Post: deanhystad
  Tkinter Exit Code based on Entry Widget Nu2Python 6 2,871 Oct-21-2021, 03:01 PM
Last Post: Nu2Python
  method to add entries in multi columns entry frames in self widget sudeshna24 2 2,212 Feb-19-2021, 05:24 PM
Last Post: BashBedlam
  Entry Widget issue PA3040 16 6,647 Jan-20-2021, 02:21 PM
Last Post: pitterbrayn
  [Tkinter] Get the last entry in my text widget Pedroski55 3 6,294 Jul-13-2020, 10:34 PM
Last Post: Pedroski55
  How to retreive the grid location of an Entry widget kenwatts275 7 4,474 Apr-24-2020, 11:39 PM
Last Post: Larz60+
  POPUP on widget Entry taratata2020 4 3,669 Mar-10-2020, 05:04 PM
Last Post: taratata2020
  Transfer Toplevel window entry to root window entry with TKinter HBH 0 4,420 Jan-23-2020, 09:00 PM
Last Post: HBH
  The coordinates of the Entry widget (canvas) when moving berckut72 8 5,848 Jan-07-2020, 09:26 AM
Last Post: berckut72

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020