How to clear listbox entries when pressing a button? - python

I am using a Listbox in order to display some text when I press a button. However, when I press this button again to re-display, it just puts the text below the original text in the listbox. I have searched for ways to fix this problem but I cannot seem to find one that works for my specific program. The point of my program is to check a password entered by a user.
Here is my code:
#!/usr/bin/env python
#Imports
from tkinter import *
from random import *
import string
#Root And GUI Title
root = Tk()
root.wm_title("Password Checker")
#Top Frame
topFrame = Frame(root)
topFrame.grid(row=0)
#Bottom Frame And Geometry And Check Labels
bottomFrame = Frame(root)
bottomFrame.grid(row=10)
root.geometry("1000x1000")
checkLabel = Label(root)
checkCap = Label(root)
checkLow = Label(root)
checkSymb = Label(root)
checkDig = Label(root)
listbox = Listbox(root)
listbox.grid(row=6, column=1)
#Checker Function
def checker():
if len(passEntry.get()) < 8 or len(passEntry.get()) > 24:
listbox.insert(END, "Invalid Length")
listbox.grid(row=1, column=1)
if len(passEntry.get()) >= 8 and len(passEntry.get()) <= 24:
#checkLabel.config(text="Valid Length")
#checkLabel.grid(row=10, column = 1)
listbox.insert(END, "Valid Length")
cap = re.search("[A-Z]", passEntry.get())
if cap:
#checkCap.config(text="Okay Capitals")
#checkCap.grid(row=11, column = 1)
listbox.insert(END, "Okay Capitals")
else:
#checkCap.config(text="No Capitals")
#checkCap.grid(row=11, column = 1)
listbox.insert(END, "No Capitals")
low = re.search("[a-z]", passEntry.get())
if low:
#checkLow.config(text="Okay Lowercase")
#checkLow.grid(row=12, column = 1)
listbox.insert(END, "Okay Lowercase")
else:
#checkLow.config(text="No Lowercase")
#checkLow.grid(row=12, column = 1)
listbox.insert(END, "No Lowercase")
symb = re.search("[!£$%^&*()]", passEntry.get())
if symb:
#checkSymb.config(text="Okay Symbols")
#checkSymb.grid(row=13, column= 1)
listbox.insert(END, "Okay Symbols")
else:
#checkSymb.config(text="No Symbols")
#checkSymb.grid(row=13, column = 1)
listbox.insert(END, "No Symbols")
dig = re.search("[0-9]", passEntry.get())
if dig:
#checkDig.config(text="Okay Digits")
#checkDig.grid(row=14, column = 1)
listbox.insert(END, "Okay Digits")
else:
#checkDig.config(text="No Digits")
#checkDig.grid(row=14, column = 1)
global noDigits
noDigits = listbox.insert(END, "No Digits")
#Password Entry
passEntryLabel = Label(root, text="Password")
passEntryLabel.grid(row=0, column=3)
passEntry = Entry(root)
PAR = passEntry.get()
passEntry.grid(row=0, column=4)
checkButton = Button(root, text="Check Password", command=checker)
checkButton.grid(row=0, column=7)
#Mainloop
root.mainloop()
When I enter a first password:
First Password Entry
When I enter a second password:
Second Password Entry
After entering the second password it just puts the next set of checks below the old ones, so how would I make it that the old set gets deleted when entering the second password? Thanks.

Simply add the documented:
listbox.delete('0', 'end')
in order to delete all entries in listbox to, -- the method that updates your Listbox, checker as the first line.

Related

Guess the number with Tkinter, Python3

here is my code:
from tkinter import *
import random
def initGame():
window = Tk()
window.title("Guess the number game")
lbl = Label(window, text="Guess number from 1 to 100. Insert how many tries would you like to have: ", font=("",16))
lbl.grid(column=0, row=0)
txt = Entry(window, width=10)
txt.grid(column=0, row=1)
txt.focus() #place cursor auto
def clicked():
number_dirty = txt.get()
tries = int(number_dirty)
playGame(tries)
btn = Button(window, text="Start", command=clicked)
btn.grid(column=0, row=2)
window.geometry('800x600')
window.mainloop()
def playGame(tries):
number_of_tries = int(tries)
number = random.randint(1,100)
higher_notification = "Number is HIGHER"
lower_notification = "Number is LOWER"
game_window = Tk()
game_window.title("Game Window")
lbl = Label(game_window, text="Guess numbers between 1 and 100, you have %s tries !" %(number_of_tries), font=("",14))
lbl.grid(column=0, row=0)
txt = Entry(game_window, width=10)
txt.grid(column=0, row=1)
txt.focus()
print(number)
print(number_of_tries)
def clicked():
user_input = txt.get()
compareNumbers(number, user_input)
btn_try = Button(game_window, text="Try!", command="clicked")
btn_try.grid(column=0, row=2)
def compareNumbers(number, user_input):
if user_input == number:
messagebox.showinfo('You have won!', 'Right! the number was %s ' %(number))
else:
if user_input > number:
lbl.configure(lower_notification)
number_of_tries -1
else:
lbl.configure(higher_notification)
number_of_tries -1
game_window.geometry('600x600')
game_window.mainloop()
initGame()
On the first screen (initGame) everything works fine, when I click the button I do indeed get the second screen, which displays all objects normally. When I click the button in the game screen I get no feedback at all, nothing happens.
What am I missing?
Thank you very much !
The problem is in this line:
btn_try = Button(game_window, text="Try!", command="clicked")
Note that the command "clicked" is inside quotaions marks and therefor a string and not the method you tried to reference. What you want is:
btn_try = Button(game_window, text="Try!", command=clicked)

Using get() function on tkinter entry widget

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

How to check if only one statement equals 0?

I got some trouble with finding the matching if-statement to check if only one entry equals 0 of 3.
Here's the code:
def thanx(self):
if len(self.e.get()) == 0:
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
It is only checking if my variable e equals 0, but i actually got 2 more entries. I know i could check every single one individually, however there has to be an easier way of doing this.
Im using "tkinter" btw, but this shouldnt be too much important.
I tried it with or but this isn't working or I'm doing it wrong.
(Also tried to solve this with lambda, but again just errors...)
Maybe someone can help me there...
Edit:
I might have explained this a bit confusing, I'll add the rest of the code here that you can understand this better:
from tkinter import Tk, Label, Entry, Button, W
from tkinter import messagebox
class MyForm:
def thanx(self):
if len(self.e.get()) == 0:
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
def callback(self):
#print("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get()))
if self.boo:
f = open("PrivatData.txt", "w+")
f.write("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get()))
def __init__(self):
self.root = Tk()
self.root.title("Your privat details")
Label(self.root, text="Your Name").grid(row = 0, padx = 12, pady=5)
Label(self.root, text="Password").grid(row=1, padx=12, pady=5)
Label(self.root, text="Email").grid(row=2, padx=12, pady=5)
self.e = Entry(self.root)
self.e2 = Entry(self.root)
self.e3= Entry(self.root)
self.e.grid(row=0,column=1,columnspan=2)
self.e2.grid(row=1, column=1, columnspan=2)
self.e3.grid(row=2, column=1, columnspan=2)
self.e.focus_set()
self.show= Button(self.root, text="Submit", command=lambda:[self.thanx(),self.callback()])
self.quit = Button(self.root,text="Quit", command = self.root.quit)
self.show.grid(row=3, column=1, pady=4)
self.quit.grid(row=3, column=2, sticky = W, pady=4)
self.root.geometry("230x140")
self.root.configure(background= "#65499c")
self.root.mainloop()
if __name__ == "__main__":
app= MyForm()
Use any:
if any((len(self.e.get().strip())==0,len(self.e2.get().strip())==0,len(self.e2.get().strip())==0)):
do stuff to say that user did not input all fields
else:
do stuff to say that user inputted all fields
So full code:
from tkinter import Tk, Label, Entry, Button, W
from tkinter import messagebox
class MyForm:
def thanx(self):
if any((len(self.e.get().strip())==0,len(self.e2.get().strip())==0,len(self.e2.get().strip())==0)):
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
def callback(self):
#print("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get()))
if self.boo:
f = open("PrivatData.txt", "w+")
f.write("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get()))
def __init__(self):
self.root = Tk()
self.root.title("Your privat details")
Label(self.root, text="Your Name").grid(row = 0, padx = 12, pady=5)
Label(self.root, text="Password").grid(row=1, padx=12, pady=5)
Label(self.root, text="Email").grid(row=2, padx=12, pady=5)
self.e = Entry(self.root)
self.e2 = Entry(self.root)
self.e3= Entry(self.root)
self.e.grid(row=0,column=1,columnspan=2)
self.e2.grid(row=1, column=1, columnspan=2)
self.e3.grid(row=2, column=1, columnspan=2)
self.e.focus_set()
self.show= Button(self.root, text="Submit", command=lambda:[self.thanx(),self.callback()])
self.quit = Button(self.root,text="Quit", command = self.root.quit)
self.show.grid(row=3, column=1, pady=4)
self.quit.grid(row=3, column=2, sticky = W, pady=4)
self.root.geometry("230x140")
self.root.configure(background= "#65499c")
self.root.mainloop()
if __name__ == "__main__":
app= MyForm()
I am assuming that at the moment you are checking if some string element equals 0.
For example
e = 'abc'
len(e) == 3 # True
l = []
len(l) == 0 # True
If you want to check if your string variable is 0 then simply:
if not self.e.get():
messagebox.showerror("Error")
self.boo = False
You may try this:
if len(self.e.get()) == 0 or len(self.e2.get()) == 0 or len(self.e3.get()) == 0:
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
Since you have 3 variables, there's no way to check them all 'in batch' unless you build a data structure containing them and then check some conditions on that data structure. However, it does not give any advantage. If you add a new variable, say e4, you still have to add it manually to the the data structure.
To ensure that all three textboxes are not empty in one if statement, you can use the following:
if "" in [self.e.get().strip(), self.e2.get().strip(), self.e3.get().strip()]:
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
This is a short and neat way to write what you are trying to do. This works because entry widgets will return "" if they are empty, and self.e.get().strip() makes the text returned empty (.strip() removes all whitespace at both the start and the end of the string) if it is just whitespace (" ", \t, n, etc...).
It is better to check the contents of the string rather than the length of it, because a box with just whitespace in it will not return 0, as shown below.
>>> len(" ")
1
>>> len("")
0
>>> len("\t")
1

Python Tkinter- Direct pointer back to Entry() box

When A user inputs a blank string of text I can either pop up a new input box which looks nasty or, like a webpage, direct the cursor back into the Entry() box
Unfortunately after searching I am still completely clueless as to how I can achieve this direction of the cursor.
My code looks like this-
import time
from tkinter import *
root = Tk()
##Encrypt and Decrypt
Master_Key = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#£$%&'()*+,-./:;?#[\\]^_`{|}~\t\n\r\x0b\x0c"
def Encrypt(User_Input, Key):
Output = ""
for i in range(len(User_Input)):
Ref_For_Output = Master_Key.index(User_Input[i]) + Master_Key.index(Key[i])
if Ref_For_Output >= len(Master_Key):
Ref_For_Output -= len(Master_Key)
Output += Master_Key[Ref_For_Output]
return Output
def Decrypt(User_Input, Key):
Output = ""
for i in range(len(User_Input)):
Ref_For_Output = Master_Key.index(User_Input[i]) - Master_Key.index(Key[i])
if Ref_For_Output < 0:
Ref_For_Output += len(Master_Key)
Output += Master_Key[Ref_For_Output]
return Output
##def popup():
## main = Tk()
## Label1 = Label(main, text="Enter a new key: ")
## Label1.grid(row=0, column=0)
## New_Key_Box = Entry(main, bg="grey")
## New_Key_Box.grid(row=1, column=0)
##
## Ok = Button(main, text="OK", command=Set_Key(New_Key_Box.get()))
##
## Ok.grid(row=2, column=0)
## if
## main.geometry("100x300")
## main.mainloop()
## return New_Key_Box.get()
class MyDialog:
def __init__(self, parent):
top = self.top = Toplevel(parent)
Label(top, text="Value").pack()
self.e = Entry(top)
self.e.pack(padx=5)
b = Button(top, text="OK", command=self.ok)
b.pack(pady=5)
def ok(self):
print( "value is" + self.e.get())
return self.e.get()
self.top.destroy()
def Compatibility(User_Input, Key):
while Key == "":
root = Tk()
Button(root, text="Hello!").pack()
root.update()
d = MyDialog(root)
print(d.ok(Key))
root.wait_window(d.top)
Temp = 0
while len(Key) < len(User_Input):
Key += (Key[Temp])
Temp += 1
return Key
##Layout
root.title("A451 CAM2")
root.geometry("270x80")
Label1 = Label(root, text="Input: ")
Label1.grid(row=0, column=0, padx=10)
Label2 = Label(root, text="Key: ")
Label2.grid(row=1, column=0, padx=10)
Input_Box = Entry(root, bg="grey")
Input_Box.grid(row=0, column=1)
Key_Box = Entry(root, bg="grey")
Key_Box.grid(row=1, column=1)
def Encrypt_Button_Press():
User_Input = Input_Box.get()
Key = Compatibility(User_Input, Key_Box.get())
print(User_Input)
root.clipboard_append(Encrypt(User_Input, Key))
Encrypt_Button.configure(text="Encrypting")
messagebox.showinfo("Complete", "Your encrypted text is: \n" + Encrypt(User_Input, Key) + "\n The text has been added to your clipboard.")
Encrypt_Button.configure(text="Encrypt")
#popup()
def Decrypt_Button_Press():
User_Input = Input_Box.get()
Key = Key = Compatibility(User_Input, Key_Box.get())
print(User_Input)
root.clipboard_append(Decrypt(User_Input, Key))
Decrypt_Button.configure(text="Decrypting")
messagebox.showinfo("Complete", "Your Decrypted text is: \n" + Decrypt(User_Input, Key) + "\n The text has been added to your clipboard.")
Decrypt_Button.configure(text="Decrypt")
Encrypt_Button = Button(text="Encrypt", command=Encrypt_Button_Press)
Encrypt_Button.grid(row=0, column=3, padx=10)
Decrypt_Button = Button(text="Decrypt", command=Decrypt_Button_Press)
Decrypt_Button.grid(row=1, column = 3, padx=10)
root.mainloop()
In the compatibility function I am wanting to change the while Key == "":
to pop-up a message (that's easy) and to direct the cursor back to the Key_Box( I may also make it change to red or something)
So- does anyone know how I can achieve redirection of the cursor?
Edit:I am not sure whether this is included anywhere in Tkinter, I can use tab to switch between Entry() boxes so I assume that they function in roughly the same way as other entry boxes across different platforms.
You could call .focus() on the entry? It won't move the cursor, but the user would be able to just start typing away in the entry box as if they had clicked in it.

Why do I have to click the button more than once? tkinter gui

Hi I have created a GUI using tkinter, it accepts entry from users.
I have created my own presence checks and 'spelling' checks to ensure that the user only enters accepted values.
But each time that I enter these values it makes the user click on the submit button multiple times before the output screen comes up.
Is this because I have used multiple functions?
Are there any other ways to do this?
def Search():
global E1, E2, E3, E4, file
def PresenceValidation():
if E1.get() ==(''):
root2=Tk()
errortext = Label(root2, text = "Please enter eye colour")
errortext.pack()
elif E2.get() ==(''):
root2=Tk()
root2.configure(bg="white")
errortext = Label(root2, text = "Please enter age")
errortext.pack()
elif E3.get() ==(''):
root2=Tk()
root2.configure(bg="white")
errortext = Label(root2, text = "Please enter hair colour")
errortext.pack()
elif E4.get() ==(''):
root2=Tk()
root2.configure(bg="white")
errortext = Label(root2, text = "Please enter shoesize")
errortext.pack()
else:
button = Button(root, text = "Submit information", command=SpellCheck)
button.grid(row=3, column=2, padx = 5)
def SpellCheck():
if E1.get().lower() not in ('blue', 'brown', 'green'):
root2=Tk()
root2.configure(bg="white")
errortext = Label(root2, text = "Please enter eye colour")
message= Label(root2, text = "Blue, Brown or Green")
errortext.pack()
message.pack()
elif E2.get().lower() not in ('10-20', '20-30', '30-40','40+'):
root2=Tk()
root2.configure(bg="white")
errortext = Label(root2, text = "Please enter a valid age group")
message=Label(root2, text = "10-20, 20-30, 30-40 or 40+")
errortext.pack()
message.pack()
elif E3.get().lower() not in ('Brown', 'Black', 'Blonde', 'Auburn'):
root2=Tk()
root2.configure(bg="white")
errortext = Label(root2, text = "Please enter a valid hair colour")
message = Label(root2, text = "Brown, Black, Blonde or Auburn")
errortext.pack()
message.pack()
elif E4.get().lower() not in ('1', '2', '3','4','5','6','7','8+'):
root2=Tk()
root2.configure(bg="white")
errortext = Label(root2, text = "Please enter a valid shoesize")
message = Label(root2, text = "1,2,3,4,5,6,7,8+")
errortext.pack()
message.pack()
else:
submitbutton = Button(window, text = "Submit information", command=Submit)
submitbutton.grid(row=3, column=2, padx = 5)
root = Tk()
root.title ("Search for matches")
#text that will be shown to the user
root.configure(bg="white")
Label(root, text="Please enter eye colour").grid(row=0)
Label(root, text="Please enter age").grid(row=1)
Label(root, text="Please enter hair colour").grid(row=2)
Label(root, text="Please enter shoesize").grid(row=3)
#Create user entry points
E1= Entry(root)
E2= Entry(root)
E3= Entry(root)
E4= Entry(root)
# locating input boxes to area on the screen
E1.grid(row=0, column=1)
E2.grid(row=1, column=1)
E3.grid(row=2, column=1)
E4.grid(row=3, column=1)
submitbutton = Button(window, text = "Submit information", command=PresenceValidation)
submitbutton.grid(row=3, column=2, padx = 5)
def Quit():
window.destroy()
quitbton = Button (window, text ="QUIT", command=Quit)
quitbton.grid(row=3, column=3, padx=5)
You can rewrite this to omit a lot of the code and still have it function the way you want it. The reason you're getting multiple buttons is because you're making multiple buttons. Three of them, if I counted them all. The initial Submit button should call a function that validates the fields and breaks out of the loop if it runs across an incorrect value. You can also use a Messagebox to prompt the user where the error is.
And if you don't add the Messagebox and want to keep it as is, you should change the root2 instance to a Toplevel widget to avoid creating two instances of Tkinter. This could also cause unintended results.
Here's an example of how simple you could make your presence check:
from tkMessageBox import showwarning
def PresenceValidation():
#Make dictionary to hold values
values = {'Eye color': E1.get(),
'Age': E2.get(),
'Hair': E3.get(),
'Shoesize': E4.get()
}
#Iterate over dictionary to check for empty items
for k,v in values.iteritems():
if v == '':
showwarning('Empty Value Alert', #Create alert message
k + ' needs a value') #for the first empty value,
break #and break out of the loop
Part of your problem is that you are creating more than one root window. Tkinter isn't designed to work that way. If you need more windows, create instances of Toplevel.

Categories