I have some code which asks the user to enter a word they'd like to encrypt and then the program will encrypt the word and display it on a label.
I was wondering why the following code works:
import tkinter
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
letters += letters.lower()
encryption_code += encryption_code.lower()
window = tkinter.Tk()
encryption_code_entry = tkinter.Entry(window)
entry = tkinter.Entry(window)
enc = dict(zip(letters,encryption_code))
string = 'hello world'
encr = "".join([enc.get(ch, ch) for ch in string])
def encrypt():
encrypt_label.pack()
entry.pack()
encrypt_confirm.pack()
encrypt_button.destroy()
def display_encrypt():
display_enc = encr
encrypted_label.pack()
new_message.config(text=str(display_enc))
new_message.pack()
encrypt_confirm = tkinter.Button(window, text="Confirm", command=display_encrypt)
new_message = tkinter.Label(window, text="", font=('Helvetica', 10))
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + " has been encrypted into the following: ")
encrypt_button = tkinter.Button(window, text="Encrypt", command=encrypt)
encrypt_button.pack()
encrypt_label = tkinter.Label(window, text="Please enter the message you'd like to encrypt", font=('Helvetica', 14))
window.mainloop()
But if I change string = 'hello world' (which is what I'd like to do) to string = entry.get() nothing is displayedonnew_message`. Also,
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + "has been encrypted into the following: ")
doesn't display what the user typed in the entry box so I'm almost 100% sure I'm misusing the entry.get() function.
You in fact need to have the entry.get() under display_encrypt().
Every time the encrypt_confirm button is pressed, it calls display_encrypt which will then in turn be able to get the current string in entry every time it is pressed by the user.
I edited your code a bit and it seems to be working.
Notice that I have removed string and encr as they were now redundant variables.
import tkinter
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
letters += letters.lower()
encryption_code += encryption_code.lower()
window = tkinter.Tk()
encryption_code_entry = tkinter.Entry(window)
entry = tkinter.Entry(window)
enc = dict(zip(letters,encryption_code))
string = 'hello world'
def encrypt():
encrypt_label.pack()
entry.pack()
encrypt_confirm.pack()
encrypt_button.destroy()
def display_encrypt():
display_enc = "".join([enc.get(ch, ch) for ch in entry.get()])
encrypted_label.pack()
new_message.config(text=str(display_enc))
new_message.pack()
encrypt_confirm = tkinter.Button(window, text="Confirm", command=display_encrypt)
new_message = tkinter.Label(window, text="", font=('Helvetica', 10))
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + " has been encrypted into the following: ")
encrypt_button = tkinter.Button(window, text="Encrypt", command=encrypt)
encrypt_button.pack()
encrypt_label = tkinter.Label(window, text="Please enter the message you'd like to encrypt", font=('Helvetica', 14))
window.mainloop()
You are calling entry.get() well before the user ever has a chance to enter anything. You need to call it and reset the label in response to an event, such as the user pressing <Return>, clicking a button, etc.
Related
I have this code, the problem is that when I finish the program and start again, it does not save the email on the screen, only in email.txt.
How can I add the email and password on the screen, being that even when I restart the file the email still appears on the screen, not only in email.txt?
from tkinter import *
from tkinter import messagebox
import tkinter.messagebox
roots = Tk()
roots.title("Email's save")
roots.geometry("500x500")
e = Entry(roots)
e.grid(row=0, column=1)
e.focus_set()
p = Entry(roots, show="*")
p.grid(row=1, column=1)
p.focus_set()
textEmail = StringVar()
textPassword = StringVar()
def callback():
textEmail.set(textEmail.get() + e.get() + "\n")
textPassword.set(textPassword.get() + p.get() + "\n")
def cleargrid():
textEmail.set("")
textPassword.set("")
def delete():
answer = tkinter.messagebox.askquestion('Delete', 'Are you sure you want to delete this entry?')
if answer == 'yes':
cleargrid()
def save():
email_info = e.get()
password_info = p.get()
file = open("emails.txt", "a")
file.write(email_info)
file.write("\n")
file.write(password_info)
file.write("\n")
file.write("=" * 20)
file.close()
def EmailPassword():
email = Label(roots, text="Email: ", font=('Courier', 14))
email.grid(row=0, sticky=W)
passoword = Label(roots, text="Password: ", font=('Courier', 14))
passoword.grid(row=1, sticky=W)
saved_email = Label(roots, text="Saved Email", font=('Courier', 14))
saved_email.grid(row=15, column=0)
saved_password = Label(roots, text="Password", font=('Courier', 14))
saved_password.grid(row=15, column=15)
write_email = Label(roots, textvariable=textEmail, font=('Courier', 14))
write_email.grid(row=20, column=0)
write_password = Label(roots, textvariable=textPassword, font=('Courier', 14))
write_password.grid(row=20, column=15)
btn_save = Button(roots, text="Save", command= lambda:[callback(), save()])
btn_save.grid(row=10, column=2, sticky=W)
btn_del = Button(roots, text="X", fg="red", command=delete)
btn_del.grid(row=60, column=20)
roots.mainloop()
EmailPassword()
Delete your current 'emails.txt'. It isn't formatted properly for the below to work.
Change save to this. Note the \n after your =*20
def save():
with open("emails.txt", "a") as f:
f.write(f'{e.get()}\n{p.get()}\n{"="*20}\n')
Add this function
def get_emails():
try:
with open("emails.txt", "r") as f:
for i, line in enumerate(filter(lambda t: t != f'{"="*20}\n', f.readlines())):
if not i%2:
textEmail.set(f'{textEmail.get()}{line}')
else:
textPassword.set(f'{textPassword.get()}{line}')
except FileNotFoundError:
pass
Add this line right before roots.mainloop()
get_emails()
aside:
Are you really going to store non-encrypted email and password information in a text file?
In order for the email address to appear at the beginning, you have to get that information from the file. Just add another function that opens the file (if present), reads the address and sets the variable textEmail
def set_email():
try:
file = open("emails.txt", "r")
emails = file.readlines()
last_address = emails[-2][:-1] # line before last line without the line break
file.close()
textEmail.set(last_address)
except:
pass ## There was no file "emails.txt"
If you call this function after the variable textEmail is defined, you will have the address when the window is loaded.
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)
I can't generate the number because I get the error NameError: name 'z' is not defined.
import tkinter as tk
from random import randint
def randomize():
z.set ( randint(x.get(),y.get()))
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root)
enterY = tk.Entry(root)
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I need help to resolve the error
You have 2 problems here.
One. You are missing z = tk.Intvar() in the global namespace.
Two. You need to assign each entry field one of the IntVar()'s.
Keep in mind that you are not validating the entry fields so if someone types anything other than a whole number you will run into an error.
Take a look at this code.
import tkinter as tk
from random import randint
def randomize():
z.set(randint(x.get(),y.get()))
print(z.get()) # added print statement to verify results.
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar() # added IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root, textvariable=x) # added textvariable
enterY = tk.Entry(root, textvariable=y) # added textvariable
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I'd like to know how to get/limit the amount of characters typed into an entry box then run a block of code if it equals a certain value. I've tried this and got nothing.
import tkinter
window = tkinter.Tk()
encryption_code_entry = tkinter.Entry(window)
code_count = encryption_code_entry.get().upper()
code_count.split()
len(code_count.split())
def change_code():
for i in code_count:
if code_count == 26:
incorrect_label.destroy()
encryption_code = encryption_code_entry.get()
new_encryption_confirm.config(text="")
new_encryption_label.config(text="You have successfully changed the encryption code")
new_encryption_label.config(text="Please press the back button to return to the main menu")
elif code_count != 26:
incorrect_label.pack()
encryption_code_entry.pack()
new_encryption_label = tkinter.Label(window, text="Please enter your own encryption code in block capitals", font=('Helvetica', 14))
new_encryption_label.pack()
new_encryption_label2 = tkinter.Label(window, text="Make sure it is all 26 letters and do not repeat a letter to prevent errors", font=('Helvetica', 14))
new_encryption_label2.pack()
new_encryption_confirm = tkinter.Button(window, text="Confirm", command=change_code)
new_encryption_confirm.pack()
incorrect_label = tkinter.Label(window, text="You didn't enter all 26 characters, please try again", font=('Helvetica', 14))
window.mainloop()
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.