this is a software that you ill have to login ells i will shut-down
i used the threading so the Tk gui.would keep on going
but it wont stop after 0. its not a problem its just iterating me knowing its in the background. so is there any way to get it to stop.


and is there any way to use a **** password font for the entry.

# -*- coding: cp1252 -*-
#user/bin/python!

import threading

import os
from Tkinter import *
from time import *




    




#os.system("shutdown -s")


class loginScreen:
    def __init__(self):

        def log():

            if self.user.get() == 'XXXX' and self.password.get()== 'XXXXX':
                main()
                self.root.destroy()                                
                print 'welcome'               
            else:
                print 'wrong password'


            
        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()
       

        #self.root.protocol('WM_DELETE_WINDOW', self.root)
        self.root.title('Login')
        self.root.geometry('300x200+270+50')
        self.userlabel = Label(self.root,text='Användarnamn')
        self.user = Entry(self.root)
        self.passwordlab = Label(self.root,text='lösenord')
        self.password = Entry(self.root)
        self.Time = Label(self.root,textvariable = self.str_1,fg='green',bg='black')
        self.Time.pack()
        self.userlabel.pack()
        self.user.pack()
        self.passwordlab.pack()
        self.password.pack()
        self.logon = Button(self.root,text = 'Login',command = log)
        self.logon.pack()

     



        def count(self):
            while True:
                sleep(1.0) # give mainloop time to start
                Time = 59
                inloged = False
                while not inloged:                        
                    sleep(1)
                    Time -= 1
                    print self.str_1.get()
                    self.str_1.set('stänger av om: ' + str (Time))      
                    if Time == 0:
                        print 'bye bye :)'
                        inloged = True                       
                        self.root.destroy()
                
        self.t = threading.Thread(target=count, args=(self.root,))
        self.t.setDaemon(True)
        self.t.start()         
                
        self.root.mainloop()

        


    

##===============================================================
if "__main__" == __name__  :
   LS=loginscreen()

Recommended Answers

All 14 Replies

I suggest

self.root.destroy()
                        break

to exit the while loop.

edit: sorry, there are 2 while loops. What's the use of the while True ?

Threading is not necessary. You can just use a while loop and exit after a certain amount of time or number of guesses.

class LoginScreen:
    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('Login')
        self.root.geometry('300x200+270+50')
        self.userlabel = Label(self.root,text='Anvandarnamn')
        self.user = Entry(self.root)
        self.passwordlab = Label(self.root,text='losenord')
        self.password = Entry(self.root, show="*")
        self.Time = Label(self.root,textvariable = self.str_1,fg='green',bg='black')
        self.Time.pack()
        self.userlabel.pack()
        self.user.pack()
        self.passwordlab.pack()
        self.password.pack()
        self.logon = Button(self.root,text = 'Login',command = self.log)
        self.logon.pack()

        ## commented because this has nothing to do
        ##  with time, but subtracts one for every guess
        ##Time = 59
        self.guesses_left = 5
        self.str_1.set(str(self.guesses_left))
        self.root.mainloop()
        while self.guesses_left > 0:
            print self.guesses_left

        print 'bye bye :)'

##        self.t = threading.Thread(target=count, args=(self.root,))
##        self.t.setDaemon(True)
##        self.t.start()


    def log(self):
            if self.user.get() == 'XXXX' and self.password.get()== 'XXXXX':
                self.root.destroy()
                print 'welcome'
                self.guesses_left = 0
            else:
                print 'wrong password'
                self.guesses_left -= 1
                self.str_1.set(str(self.guesses_left))

##===============================================================
if "__main__" == __name__  :
   LS=LoginScreen()

See here for entry widget options
http://effbot.org/tkinterbook/entry.htm

Just to make it interesting, this is the same code, but it stops after 5 tries or one minute. It uses multiprocessing (pyprocessing for Python 2.5), instead of threading which is easier and better IMHO. You have to pass an object to the process, in this case a dictionary with the keyword 'QUIT', which can be accessed both inside and outside of the process if you want to limit the number of quesses and have a time limitation. The commented code under "__main__" can be used if you just want a time limitation. Note that you would also have to remove the 'test_d' dictionary from the class' code as well.

from multiprocessing import Process, Manager

import os
from Tkinter import *
import datetime
import time

class LoginScreen:
    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('Login')
        self.root.geometry('300x200+270+50')
        self.userlabel = Label(self.root,text='Anvandarnamn')
        self.user = Entry(self.root)
        self.passwordlab = Label(self.root,text='losenord')
        self.password = Entry(self.root, show="*")
        self.Time = Label(self.root,textvariable = self.str_1,fg='green',bg='black')
        self.Time.pack()
        self.userlabel.pack()
        self.user.pack()
        self.passwordlab.pack()
        self.password.pack()
        self.logon = Button(self.root,text = 'Login',command = self.log)
        self.logon.pack()

        ##--- start the process with a manager dictionary
        tries = 5
        manager = Manager()
        test_d = manager.dict()
        test_d["QUIT"] = False
        p = Process(target=self.get_password, args=(test_d, tries,))
        p.start()

        start_time = datetime.datetime.now()
        stop_time = start_time + datetime.timedelta(minutes = 1)
        print start_time, stop_time
        time_to_stop = False
        while (not test_d['QUIT']) and (not time_to_stop):
           now = datetime.datetime.now()
           if stop_time < now:
              time_to_stop = True
              print "time to stop"
           time.sleep(0.1) ## eliminate some unnecessary processor cycles
        p.terminate()


    def get_password(self, test_d, tries):
        self.test_d = test_d
        print test_d
        self.guesses_left = tries
        self.str_1.set(str(self.guesses_left))
        self.root.mainloop()

        print 'bye bye :)'


    def log(self):
            print self.guesses_left
            if self.user.get() == 'XXXX' and self.password.get()== 'XXXXX':
                print 'welcome'
##                self.root.destroy()
                self.guesses_left = 0
                self.test_d['QUIT'] = True
            else:
                print 'wrong password'
                self.guesses_left -= 1
                self.str_1.set(str(self.guesses_left))

            if (self.guesses_left < 1):
               self.test_d['QUIT'] = True
##               self.root.destroy()

##===============================================================
if "__main__" == __name__  :
   LS=LoginScreen()

   """------- without just a time limitation
   tries=5
   p = Process(target=LS.get_password, args=(tries,))
   p.start()

   ## sleep for 20 seconds and terminate
   time.sleep(20.0)
   p.terminate()

   ##---- one minute or correct password
   manager = Manager()
   test_d = manager.dict()
   test_d["QUIT"] = False
   p = Process(target=LS.get_password, args=(test_d,tries ,))
   p.start()

   start_time = datetime.datetime.now()
   stop_time = start_time + datetime.timedelta(minutes = 1)
   print start_time, stop_time
   time_to_stop = False
   while (not test_d['QUIT']) and (not time_to_stop):
      now = datetime.datetime.now()
      if stop_time < now:
         time_to_stop = True
         print "time to stop"
      time.sleep(0.1) ## eliminate some unnecessary processor cycles
   p.terminate()
   """

I suggest

self.root.destroy()
                        break

to exit the while loop.

edit: sorry, there are 2 while loops. What's the use of the while True ?

I don't need it so ill just delete it thanks for help

Just to make it interesting, this is the same code, but it stops after 5 tries or one minute. It uses multiprocessing (pyprocessing for Python 2.5), instead of threading which is easier and better IMHO. You have to pass an object to the process, in this case a dictionary with the keyword 'QUIT', which can be accessed both inside and outside of the process if you want to limit the number of quesses and have a time limitation. The commented code under "__main__" can be used if you just want a time limitation. Note that you would also have to remove the 'test_d' dictionary from the class' code as well.

from multiprocessing import Process, Manager

import os
from Tkinter import *
import datetime
import time

class LoginScreen:
    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('Login')
        self.root.geometry('300x200+270+50')
        self.userlabel = Label(self.root,text='Anvandarnamn')
        self.user = Entry(self.root)
        self.passwordlab = Label(self.root,text='losenord')
        self.password = Entry(self.root, show="*")
        self.Time = Label(self.root,textvariable = self.str_1,fg='green',bg='black')
        self.Time.pack()
        self.userlabel.pack()
        self.user.pack()
        self.passwordlab.pack()
        self.password.pack()
        self.logon = Button(self.root,text = 'Login',command = self.log)
        self.logon.pack()

        ##--- start the process with a manager dictionary
        tries = 5
        manager = Manager()
        test_d = manager.dict()
        test_d["QUIT"] = False
        p = Process(target=self.get_password, args=(test_d, tries,))
        p.start()

        start_time = datetime.datetime.now()
        stop_time = start_time + datetime.timedelta(minutes = 1)
        print start_time, stop_time
        time_to_stop = False
        while (not test_d['QUIT']) and (not time_to_stop):
           now = datetime.datetime.now()
           if stop_time < now:
              time_to_stop = True
              print "time to stop"
           time.sleep(0.1) ## eliminate some unnecessary processor cycles
        p.terminate()


    def get_password(self, test_d, tries):
        self.test_d = test_d
        print test_d
        self.guesses_left = tries
        self.str_1.set(str(self.guesses_left))
        self.root.mainloop()

        print 'bye bye :)'


    def log(self):
            print self.guesses_left
            if self.user.get() == 'XXXX' and self.password.get()== 'XXXXX':
                print 'welcome'
##                self.root.destroy()
                self.guesses_left = 0
                self.test_d['QUIT'] = True
            else:
                print 'wrong password'
                self.guesses_left -= 1
                self.str_1.set(str(self.guesses_left))

            if (self.guesses_left < 1):
               self.test_d['QUIT'] = True
##               self.root.destroy()

##===============================================================
if "__main__" == __name__  :
   LS=LoginScreen()

   """------- without just a time limitation
   tries=5
   p = Process(target=LS.get_password, args=(tries,))
   p.start()

   ## sleep for 20 seconds and terminate
   time.sleep(20.0)
   p.terminate()

   ##---- one minute or correct password
   manager = Manager()
   test_d = manager.dict()
   test_d["QUIT"] = False
   p = Process(target=LS.get_password, args=(test_d,tries ,))
   p.start()

   start_time = datetime.datetime.now()
   stop_time = start_time + datetime.timedelta(minutes = 1)
   print start_time, stop_time
   time_to_stop = False
   while (not test_d['QUIT']) and (not time_to_stop):
      now = datetime.datetime.now()
      if stop_time < now:
         time_to_stop = True
         print "time to stop"
      time.sleep(0.1) ## eliminate some unnecessary processor cycles
   p.terminate()
   """

won't work i downloaded py processing 0.52

i tried the code but i only get this error

UnpickleableError: Cannot pickle <type 'tkapp'> objects

self.root.destroy()
                    break

still don't work need something better and not py processing.

This one seems to work

from Tkinter import *

class LoginFailed(Exception):
    pass

class LoginScreen:

    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('Login')
        self.root.geometry('300x200+270+50')
        self.userlabel = Label(self.root,text='Anvandarnamn')
        self.user = Entry(self.root)
        self.passwordlab = Label(self.root,text='losenord')
        self.password = Entry(self.root, show="*")
        self.Time = Label(self.root,textvariable = self.str_1,fg='green',bg='black')
        self.Time.pack()
        self.userlabel.pack()
        self.user.pack()
        self.passwordlab.pack()
        self.password.pack()
        self.SUCCESS = False
        self.logon = Button(self.root,text = 'Login',command = self.log)
        self.logon.pack()
        self.guesses_left = 5
        self.str_1.set(str(self.guesses_left))
        self.root.mainloop()


    def log(self):
        if not(self.user.get() == 'XXXX' and self.password.get()== 'XXXXX'):
            self.guesses_left -= 1
            self.str_1.set(str(self.guesses_left))
            if self.guesses_left:
                return
            else:
                self.root.destroy()
        else:
            self.SUCCESS = True
            self.root.destroy()

def login():
    screen = LoginScreen()
    if not screen.SUCCESS:
        raise LoginFailed

##===============================================================
if "__main__" == __name__  :
    try:
        login()
    except LoginFailed:
        print("bye bye :)")
        raise SystemExit
    print "WELCOME !"

are you misunderstanding me the label at the top is a count an when it gets to zero the program stud shut-down.and if you piked the right user name and pass than the root whill be destroyed and a new will appear(will be added after this)

:?: so can you fix it or is it impossible to make a count loop that not stops the mainloop and not just go on after Zero. ells ill just let it continue in the background

Add this at the end of my previous post

class NewWindow:

    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('New Window')
        self.root.geometry('500x400+270+50')
        self.welcome = Label(self.root,text='WELCOME')
        self.welcome.pack()
        self.root.mainloop()

NewWindow = NewWindow()

and you will see a new window appear if the login is successful.

Add this at the end of my previous post

class NewWindow:

    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('New Window')
        self.root.geometry('500x400+270+50')
        self.welcome = Label(self.root,text='WELCOME')
        self.welcome.pack()
        self.root.mainloop()

NewWindow = NewWindow()

and you will see a new window appear if the login is successful.

nonono. when i say count i mean you have some seconds to login

Ok, here it is

from Tkinter import *
import threading

class MyTimer(object):
    # Borrowed from http://guigui.developpez.com/sources/TkHorloge/
    def __init__(self, tempo, target, args= [], kwargs={}):
        self._target = target
        self._args = args
        self._kwargs = kwargs
        self._tempo = tempo

    def _run(self):
        self._timer = threading.Timer(self._tempo, self._run)
        self._timer.start()
        self._target(*self._args, **self._kwargs)
        
    def start(self):
        self._timer = threading.Timer(self._tempo, self._run)
        self._timer.start()

    def stop(self):
        self._timer.cancel()


class LoginFailed(Exception):
    pass

class LoginScreen(object):

    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('Login')
        self.root.geometry('300x200+270+50')
        self.userlabel = Label(self.root,text='Anvandarnamn')
        self.user = Entry(self.root)
        self.passwordlab = Label(self.root,text='losenord')
        self.password = Entry(self.root, show="*")
        self.Time = Label(self.root,textvariable = self.str_1,fg='green',bg='black')
        self.Time.pack()
        self.userlabel.pack()
        self.user.pack()
        self.passwordlab.pack()
        self.password.pack()
        self.SUCCESS = False
        self.logon = Button(self.root,text = 'Login',command = self.log)
        self.logon.pack()
        self.ticks_left = 10
        self.str_1.set(str(self.ticks_left))
        self.timer = MyTimer(1.0, self.tick)
        self.timer.start()
        self.root.mainloop()

    def tick(self):
        self.ticks_left -=1
        if self.ticks_left <= 0:
            self.timer.stop()
            self.root.destroy()
        else:
            self.str_1.set(str(self.ticks_left))
        

    def log(self):
        if self.user.get() == 'XXXX' and self.password.get()== 'XXXXX':
            self.timer.stop()
            self.SUCCESS = True
            self.root.destroy()

def login():
    screen = LoginScreen()
    if not screen.SUCCESS:
        raise LoginFailed



##===============================================================
if "__main__" == __name__  :
    try:
        login()
    except LoginFailed:
        print("bye bye :)")
        raise SystemExit
    print "WELCOME !"


class NewWindow(object):

    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('New Window')
        self.root.geometry('500x400+270+50')
        self.welcome = Label(self.root,text='WELCOME')
        self.welcome.pack()
        self.root.mainloop()

NewWindow = NewWindow()

many thanks to you and guigui.developpez.com
everything woks fine accept

SystemExit

Traceback (most recent call last):
File "C:/Python25/j3.py", line 90, in <module>
raise SystemExit
SystemExit

ok im using phyton35 if that's to any help

try sys.exit(0)

try sys.exit(0)

nope wont work I try to fix it by myself

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.