populate Entry using tkinter - python

I have a issue when I want to populate a entry box using tkinter. My current script are calling another script to get values. Then I want the data to be displayed in a Tkinter entry box.
This is my current code, I am have tried tbName.set("tbName", account.getName()) somethhing like that (with and without the tbName) I have also triws StringVar. I am not sure if I am using it wrong. I have looked at the following site : effbot. I am very new to Python so any help will b apritiated.
from Tkinter import *
from bank import Bank, SavingsAccount
class BankManager(object):
root = Tk()
lblName = Label(root, text="Name")
lblPin = Label(root, text="Pin")
lblBalance = Label(root, text="Balance R")
lblStatus = Label(root, text="Status")
tbName = Entry(root)
tbPin = Entry(root)
tbBalance = Entry(root)
tbStatus = Entry(root)
def __init__(self):
self.bank = None
self.app = None
self.current_index = 0
self.create_bank()
self.populate_gui(self.current_index)
def new_account(self, event):
name = self.app.getEntry('name')
pin = self.app.getEntry('pin')
balance = self.app.getEntry('balance')
account = self.bank.get(pin)
if account:
self.app.setEntry("status", "Account with pin exists")
else:
self.bank.add(SavingsAccount(name, pin, float(balance)))
self.app.setEntry("status", "New account created")
self.current_index = self.bank.getPins().index(pin)
btnNewAcc = Button(root,text="New Account")
btnNewAcc.bind("<Button>",new_account)
def update_account(self, event):
name = self.app.getEntry('name')
pin = self.app.getEntry('pin')
balance = self.app.getEntry('balance')
account = self.bank.get(pin)
if account:
account._name = name
account._balance = balance
self.app.setEntry("status", "Account updated")
else:
self.app.setEntry("status", "Account with pin doesn't exist")
btnUpdateAcc = Button(root, text="Update Account")
btnUpdateAcc.bind("<Button>",update_account)
def remove_account(self, event):
pin = self.app.getEntry('pin')
account = self.bank.get(pin)
if account:
self.bank.remove(pin)
self.app.setEntry("status", "Account removed")
self.current_index = 0
else:
self.app.setEntry("status", "Account with pin doesn't exist")
btnRemoveAcc = Button(root,text="Remove Account")
btnRemoveAcc.bind("<Button>",remove_account)
def compute_interest(self, event):
self.bank.computeInterest()
pin = self.app.getEntry('pin')
account = self.bank.get(pin)
if account:
self.app.setEntry("status", "Interest updated")
self.app.setEntry("balance", str(account.getBalance()))
else:
self.app.setEntry("status", "Account with pin doesn't exist")
btnConputeInterest = Button(root,text="Compute Interest")
btnConputeInterest.bind("<Button>",compute_interest)
def press_navigator(self, event):
if button == "Previous":
if self.current_index == 0:
self.current_index = len(self.bank.getPins()) - 1
else:
self.current_index -= 1
elif button == "Next":
if self.current_index == len(self.bank.getPins()) - 1:
self.current_index = 0
else:
self.current_index += 1
self.populate_gui(self.current_index)
btnPrevious = Button(root,text="Previous")
btnPrevious.bind("<Button>",press_navigator)
btnNext = Button(root,text="Next")
btnNext.bind("<Button>",press_navigator)
lblName.grid(row=0)
lblPin.grid(row=1)
lblBalance.grid(row=2)
lblStatus.grid(row=3)
tbName.grid(row=0, column=1)
tbPin.grid(row=1, column=1)
tbBalance.grid(row=2, column=1)
tbStatus.grid(row=3, column=1)
btnNewAcc.grid(row=0, column=2)
btnUpdateAcc.grid(row=1, column=2)
btnRemoveAcc.grid(row=2, column=2)
btnConputeInterest.grid(row=3, column=2)
btnPrevious.grid(row=4, column=0)
btnNext.grid(row=4, column=1)
root.mainloop()
def create_bank(self):
self.bank = Bank()
a1 = SavingsAccount('zzz', '111', 100)
a2 = SavingsAccount('yyy', '222', 200)
a3 = SavingsAccount('xxx', '333', 300)
self.bank.add(a1)
self.bank.add(a3)
self.bank.add(a2)
def populate_gui(self, index):
account = self.bank.get(self.bank.getPins()[index])
tbName.set("tbName", account.getName())
if __name__ == '__main__':
BankManager()

if you want to set text in the Entry widget, you need to use Entry.insert(0,'text') instead of v.set. The 0 in the insert method is the place you want to insert the text, in this case it is in the beginning of the Entry.
If you don't want the user to edit what is inside the Entry, you can use Entry.config(state='readonly'); if you want to edit the content later you need to call Entry.config(state=NORMAL) before you can use Entry.insert again. You don't need to set StringVar to the Entry, only using Entry.get() is sufficient.

Related

_tkinter.TclError: bad window path name ".!frame2"

I am making a project which is supposed to close the first window and open a new one, but I get this error in line 101 which says "d2.pack()" in the roll() function. I want to make it so whenever you press the "roll" button, the old frame with the old roll dissapears and a new one will appear in the exact same place with the new roll, before it would just appear underneath the old roll so I tried to do something to make it work, but nothing has worked yet. I have tried quite some things but nothing works. As I am quite new to coding, any help would be appreciated.
from csv import excel_tab
import sqlite3
from turtle import width
from argon2 import PasswordHasher
from tkinter import *
from tkinter import ttk
import atexit
global active_user
def raise_frame(frame):
frame.tkraise()
ph = PasswordHasher()
root = Tk()
root.geometry("750x500")
f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
for frame in (f1, f2, f3):
frame.pack()
con = sqlite3.connect("nope you're not getting this")
cur = con.cursor()
def slots():
return
def createAcc():
password = newPass.get()
usernameNew = newUser.get()
hashed_password = ph.hash(password)
cur.execute("INSERT INTO thing (user, money, password, sessionactive) VALUES (?,?,?,?)", (usernameNew, 10000, hashed_password, 0))
con.commit()
main()
def login():
global entryUsername
global entryPass
label = Label(f2, text="Enter username and password", font=("Courier 22 bold"))
label.pack(padx=0, pady=10)
entryUsername = Entry(f2, width= 40)
entryUsername.focus_set()
entryUsername.pack(padx=0, pady=10)
entryPass = Entry(f2, width= 40)
entryPass.focus_set()
entryPass.pack()
ttk.Button(f2, text= "Enter",width= 20, command=loginCheck).pack(pady=20)
raise_frame(f2)
def create():
global newUser
global newPass
label = Label(f3, text="Create username and password", font=("Courier 22 bold"))
label.pack(padx=0, pady=10)
newUser = Entry(f3, width= 40)
newUser.focus_set()
newUser.pack(padx=0, pady=10)
newPass = Entry(f3, width= 40)
newPass.focus_set()
newPass.pack()
ttk.Button(f3, text= "Enter",width= 20, command=createAcc).pack(pady=20)
raise_frame(f3)
def loginCheck():
global username
global active_user
i = 0
password = entryPass.get()
username = entryUsername.get()
cur.execute("SELECT * FROM thing")
data = cur.fetchall()
while i < len(data):
if data[i][0] == username and ph.verify(data[i][2], password) == True:
active_user = username
main()
else:
i += 1
print("Invalid username or password, please try again")
def roll():
global d2
new_frame = d2
if d2 is not None:
d2.destroy()
d2 = new_frame
d2.pack() #here's the error
Label(d2, text="test", font=("Courier 22 bold")).pack()
def main():
global root
global root2
global d1
global d2
f1.destroy()
root2 = Tk()
d1 = Frame(root2)
d2 = Frame(root2)
for frame in (d1, d2):
frame.pack()
root2.geometry("750x500")
Label(root2, text="Press roll to roll the slots", font=("Courier 22 bold")).pack(pady=20)
ttk.Button(d1, text="Roll", width=20, command=roll).pack(pady=40)
root2.mainloop()
def mainScreen():
label = Label(f1, text="Welcome to epic gambling thing!", font=("Courier 22 bold"))
label.pack(padx=0, pady=10)
ttk.Button(f1, text= "Login",width= 20, command=login).pack(pady=20)
raise_frame(f1)
ttk.Button(f1, text= "Create Account",width= 20, command=create).pack(pady=20)
mainScreen()
root.mainloop()

Is there a way to create new instances automatically?

As you can see, I can store passwords here.
I have to add a feature that I can register a new user. How do I do it so that I can create new instances when creating a new user?
import datetime
import getpass
class User:
def __init__(self, username, mail, date_of_birth, gender, password):
self.username = username
self.mail = mail
self.date_of_birth = datetime.datetime.strptime(date_of_birth, "%d.%m.%Y").date()
self.gender = gender
self.password = password
def get_username(self):
return self.username
def get_mail(self):
return self.mail
def get_date_of_birth(self):
return self.date_of_birth
def get_gender(self):
return self.gender
def get_password(self):
self.password
def get_date(self):
return self.date_of_birth
log = ""
def tries_left(self):
max_tries = 3
trie = 0
while trie <= max_tries:
print("wrong password!")
print("tries left " + str(max_tries - trie + 1))
trie +=1
pwrd = input("input password")
if pwrd != self.password:
pass
else:
self.login_or_register()
def login2(self):
global log
log = input("input your username: ")
if log == self.username:
pwrd = input("whats your password?")
if pwrd == self.password:
print("Logged in!")
self.add_password_orCheck_password()
else:
self.tries_left()
else:
print("wrong username!")
self.login2()
def login_or_register(self):
user_input = input("Login or Register: ")
if user_input == "login":
self.login2()
elif user_input == "register":
pass
else:
print("Try again!")
self.login_or_register()
def add_password(self):
global sitepassword
global Site
Site = input("Enter site name: ")
sitepassword = input("Enter password")
self.add_password_orCheck_password()
global passwords
passwords = {Site: sitepassword}
def check_passwords(self):
global passwords
global sitepassword
global Site
passwords = {Site: sitepassword}
which_password = input("Which sites password do you want to see?")
for Site in passwords:
if which_password in passwords:
print(sitepassword)
self.add_password_orCheck_password()
def add_password_orCheck_password(self):
add_new = input("Do you want to add a password or check passwords?")
if "add a password" in add_new:
self.add_password()
elif "check passwords" in add_new:
self.check_passwords()
Matt = User("Matterson", "matt#gmail.com", "21.12.1999" ,"male", "Password987")
session1 = Matt.login_or_register()
i wasnt thinking here is a better option:
users = {}
while True:
name = input('yourtexthere')
email = input('yourtexthere')
year = input('yourtexthere')
gender = input('yourtexthere')
password = input('yourtexthere') # here you will use getpass
users[f'{name}'] = User(name, email, year, gender, password)
however you can also store them in list but then you will have to access them by index and you may want to use the email as a key:
users[f'{email}'] = User(name, email, year, gender, password)
here is the code (refer to my comment) its not the cleanest one but it works, here you can try implementing your User class and making it as you need however you need experience in tkinter (this is just an example) hope it helps (it also creates the json file (if it is not already created) in this codes directory) (and I hope this aint against some guidlines):
from tkinter import *
from tkinter import messagebox
import json
all_user_pass = dict()
try:
with open('stored_data.json') as file:
data = json.load(file)
except:
with open('stored_data.json', 'w') as file:
json.dump(all_user_pass, file, indent=2)
with open('stored_data.json') as file:
data = json.load(file)
class MainWindow(Toplevel):
def __init__(self, parent):
self.parent = parent
Toplevel.__init__(self, parent)
self.x_tk = 310
self.y_tk = 100
self.win_h = int(self.winfo_screenheight()/2 - self.y_tk/2)
self.win_w = int(self.winfo_screenwidth()/2 - self.x_tk/2)
self.geometry(f"{str(self.x_tk)}x{str(self.y_tk)}+{str(self.win_w)}+{str(self.win_h)}")
self.title('Login')
self.protocol('WM_DELETE_WINDOW', self.quit)
self.username = Entry(self, bg="grey", bd=5, font="none 12 normal")
word_username = Label(self, text='Username:')
word_username.grid(row=0, column=0, sticky='w')
self.username.grid(row=0, column=1)
self.password = Entry(self, bg="grey", bd=5, font="none 12 normal")
word_password = Label(self, text='Password:')
word_password.grid(row=1, column=0, sticky='w')
self.password.grid(row=1, column=1)
login_button = Button(self, text='Login', command=self.login)
login_button.grid(row=2, column=0)
self.bind('<Return>', self.login)
signup_button = Button(self, text='Sign Up', command=self.open_signup)
signup_button.grid(row=2, column=2)
self.incorrect_user_or_pass = Label(self, text='Incorrect username or password!')
self.empty_user_or_pass = Label(self, text='Cannot be blank!')
def open_signup(self):
signupwindow = SignUpWindow(self)
signupwindow.focus_force()
signupwindow.withdraw
def login(self, event=None):
global data
existing_user = self.username.get()
user_pass = self.password.get()
self.incorrect_user_or_pass.place_forget()
if existing_user != '' and user_pass != '':
if existing_user in data and data[existing_user] == user_pass:
messagebox.showinfo('Successful Login', 'You have logged in successfully!', parent=self)
self.username.delete(0, 'end')
self.password.delete(0, 'end')
self.empty_user_or_pass.place_forget()
self.incorrect_user_or_pass.place_forget()
else:
self.username.delete(0, 'end')
self.password.delete(0, 'end')
self.empty_user_or_pass.place_forget()
self.incorrect_user_or_pass.place(x=60, y=65)
else:
self.empty_user_or_pass.place(x=90, y=65)
class SignUpWindow(Toplevel):
def __init__(self, parent):
self.parent = parent
Toplevel.__init__(self, parent)
self.x_tk = 310
self.y_tk = 100
self.win_h = int(self.parent.winfo_rooty() - 31)
self.win_w = int(self.parent.winfo_rootx() - 8)
self.geometry(f"{str(self.x_tk + 16)}x{str(self.y_tk + 39)}+{str(self.win_w)}+{str(self.win_h)}")
self.title('Signup')
self.bind('<FocusOut>', self.f_out_main)
self.bind('<Escape>', self.close)
self.update_idletasks()
self.overrideredirect(True)
self.config(bg='green')
Label(self, text='Signup', font='none 20 normal', bg='green', bd=5) .grid(row=0, column=0, columnspan=4)
self.username = Entry(self, bg="grey", bd=5, font="none 12 normal")
word_username = Label(self, text='Username:', bg='green')
word_username.grid(row=1, column=0, sticky='w')
self.username.grid(row=1, column=1)
self.username.bind('<FocusOut>', self.f_out)
self.password = Entry(self, bg="grey", bd=5, font="none 12 normal")
word_password = Label(self, text='Password:', bg='green')
word_password.grid(row=2, column=0, sticky='w')
self.password.grid(row=2, column=1)
self.password.bind('<FocusOut>', self.f_out)
cancel_button = Button(self, text='Cancel', command=self.cancel)
cancel_button.grid(row=3, column=0)
cancel_button.bind('<FocusOut>', self.f_out)
cancel_button.bind('<Return>', self.cancel)
signup_button = Button(self, text='Sign Up', command=self.signup)
signup_button.grid(row=3, column=2)
signup_button.bind('<FocusOut>', self.f_out)
self.bind('<Return>', self.signup)
self.user_taken = Label(self, text='Username already taken!', bg='green')
self.empty_user_or_pass = Label(self, text='Cannot be blank!', bg='green')
self.focus_list = []
def f_out(self, event=None):
self.focus_list.append('focus_out_of_widget')
def f_out_main(self, event=None):
self.focus_list.append('focus_out_of_window')
if len(self.focus_list) >= 2:
if self.focus_list[-2] == 'focus_out_of_window' and self.focus_list[-1] == 'focus_out_of_window':
self.close()
elif self.focus_list[0] == 'focus_out_of_window':
self.close()
def cancel(self, event=None):
self.destroy()
def signup(self, event=None):
global all_user_pass
global data
new_username = self.username.get()
new_password = self.password.get()
if new_username != '' and new_password != '':
if new_username not in data:
if new_username not in all_user_pass:
all_user_pass[new_username] = new_password
data.update(all_user_pass)
with open('stored_data.json', 'w') as f:
json.dump(data, f, indent=2)
self.username.delete(0, 'end')
self.password.delete(0, 'end')
self.user_taken.place_forget()
self.empty_user_or_pass.place_forget()
self.destroy()
else:
self.username.delete(0, 'end')
self.password.delete(0, 'end')
self.empty_user_or_pass.place_forget()
self.user_taken.place(x=90, y=110)
else:
self.username.delete(0, 'end')
self.password.delete(0, 'end')
self.empty_user_or_pass.place_forget()
self.user_taken.place(x=90, y=110)
else:
self.empty_user_or_pass.place(x=90, y=110)
def close(self, event=None):
self.parent.focus_set()
self.destroy()
root = Tk()
root.withdraw()
app = MainWindow(root)
app.mainloop()

How to close multiple Tkinter windows with one button

I am trying to build a python application. The first UGI is requesting the username and password. Then a second tk window pops up if login is successful with an okay button. Once then user press the okay button, both tk windows (the one requesting username and password and the login successful msg window) will disappear and the program continues to run.
I am very stuck with being able to press the okay button and close "both" windows. Any insights will be appreciated, thank you!
All the codes seem to be working fine. the command to execute function LoginSuccessful within the CheckLogin is able to execute the print("ANCD") but it doesn't close the two tk windows.
#import packages
import time
import openpyxl
from openpyxl import load_workbook
import tkinter as tk
from tkinter import *
import sys
def Function():
global user1
user1 = 'testing'
password1 = '0000'
def Login_form():
global username
global password
global rootA
rootA = Tk()
rootA.title('User Authentication')
msgbox1 = Label(rootA, text='Please Login\n')
msgbox1.grid(sticky=E)
username = Label(rootA, text='Username: ')
password = Label(rootA, text='Password: ')
username.grid(row=1, sticky=W)
password.grid(row=2, sticky=W)
username = Entry(rootA)
password = Entry(rootA, show='*')
username.grid(row=1, column=1)
password.grid(row=2, column=1)
login_btn = Button(rootA, text='Login', command=CheckLogin)
exit_btn=Button(rootA, text='Exit',command=sys.exit)
login_btn.grid(row=4, column=1)
exit_btn.grid(row=4, column=2)
rootA.mainloop()
def CheckLogin():
if username.get() == user1 and password.get() == password1:
rootA = Tk()
rootA.title('Authentication Cehck')
rootA.geometry('150x100') # Makes the window a certain size
rlbl = Label(rootA, text='\n Logged In')
okay_btn=Button(rootA, text='Okay',command=LoginSuccessful)
okay_btn.pack()
#LoginSuccessful()
else:
r = Tk()
r.title('Authentication Cehck')
r.geometry('150x160')
rlbl = Label(r, text='\n Invalid Login')
rlbl.pack()
okay_btn=Button(r, text='Try Again',command=r.destroy)
okay_btn.pack()
exit_btn=Button(r, text='Exit',command=sys.exit)
exit_btn.pack()
#r.mainloop()
def LoginSuccessful ():
rootA.destroy
print("ANCD")
def Insert_Rows():
for rows in range (len(All_Users_Sheet)):
if rows == 0:
rows +1
continue
if All_Users_Sheet[rows][10].value == None:
break
else:
print(All_Users_Sheet[rows][10].value)
print(type(All_Users_Sheet[rows][10].value))
Login_form()
Function()
Is there any way that after checking the username and password, if it's correct, close all tk windows by pressing a button and continue running the remaining tasks?
You should only create one instance of Tk. If you needed additional window, use Toplevel instead.
def CheckLogin():
if username.get() == user1 and password.get() == password1:
rootA = Toplevel()
rootA.title('Authentication Check')
...
else:
r = Toplevel()
...
i got one solution.
from tkinter import *
global user1
user1 = 'testing'
password1 = '0000'
def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
def Login_form():
global username
global password
global rootA
rootA = Tk()
rootA.title('User Authentication')
msgbox1 = Label(rootA, text='Please Login\n')
msgbox1.grid(sticky=E)
username = Label(rootA, text='Username: ')
password = Label(rootA, text='Password: ')
username.grid(row=1, sticky=W)
password.grid(row=2, sticky=W)
username = Entry(rootA)
password = Entry(rootA, show='*')
username.grid(row=1, column=1)
password.grid(row=2, column=1)
login_btn = Button(rootA, text='Login', command=CheckLogin)
exit_btn=Button(rootA, text='Exit',command=rootA.destroy)
login_btn.grid(row=4, column=1)
exit_btn.grid(row=4, column=2)
rootA.mainloop()
def CheckLogin():
global rootA
if username.get() == user1 and password.get() == password1:
rootA = Tk()
rootA.title('Authentication Cehck')
rootA.geometry('150x100') # Makes the window a certain size
rlbl = Label(rootA, text='\n Logged In')
okay_btn=Button(rootA, text='Okay',command=LoginSuccessful)
okay_btn.pack()
#LoginSuccessful()
else:
r = Tk()
r.title('Authentication Cehck')
r.geometry('150x160')
rlbl = Label(r, text='\n Invalid Login')
rlbl.pack()
okay_btn=Button(r, text='Try Again',command=r.destroy)
okay_btn.pack()
exit_btn=Button(r, text='Exit',command= combine_funcs(rootA.destroy, r.destroy))
exit_btn.pack()
#r.mainloop()
def LoginSuccessful ():
rootA.destroy
print("ANCD")
def Insert_Rows():
for rows in range (len(All_Users_Sheet)):
if rows == 0:
rows +1
continue
if All_Users_Sheet[rows][10].value == None:
break
else:
print(All_Users_Sheet[rows][10].value)
print(type(All_Users_Sheet[rows][10].value))
Login_form()
please dont't ask about def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
,it just solves the problem

Loading data from a file and using it in tkinter

import pickle
from tkinter import *
import tkinter.messagebox
Menu = Tk()
Menu.resizable(width=False, height = False)
Menu.state('zoomed')
Menu.title("Gold Farm")
Example = {"Test":"Initial"}
def database():
with open ("accounts.pickle", "rb") as f:
return pickle.load(f)
accounts = database()
usernameL = Label(text = "Username: ")
usernameL.place(y= 300, x = 550)
usernameB = Entry()
usernameB.place(y = 300,x = 620)
passwordL = Label(text = "Password: ")
passwordL.place(y= 330, x = 550)
passwordB = Entry(show = "*")
passwordB.place(y = 330,x = 620)
eUsername = usernameB.get()
ePassword = passwordB.get()
def confirm():
for item in accounts:
if eUsername in accounts and accounts[eUsername] == ePassword:
print("Correct")
else:
print("False")
Login = Button(text="Login", command = confirm)
Login.place(y = 350, x = 620)
This is my code that completes the following:
Asks the user for a username and password in a tkinter window
Sets whatever they inputted as eUsername and ePassword
Checks if they got the right password
Keep in mind that the 'Example' dictionary is an example of what is in the accounts files
The problem is that when I type in the correct username and password, it still returns as false.
And so;
I would like some assistance on what I'm doing wrong, or what to fix.
Test
def databaseNew():
with open("accounts.pickle", "wb") as f:
Entry = Setup["me"] = "Tes"
pickle.dump(Entry, f)
You are not getting any input in your code, if you call confirm() you will see False as you are iterating over every name in the dict with for item in accounts comparing it to an empty string. You can also simplify your function to return accounts.get(eUsername) == ePassword to check:
def confirm():
print(accounts.get(eUsername) == ePassword)
You need to pack the Labels etc..
import pickle
from tkinter import *
master = Tk()
usernameL = Label(master, text="Username: ")
usernameL.pack()
usernameB = Entry(master)
usernameB.pack()
passwordL = Label(master, text="Password: ")
passwordL.pack()
passwordB = Entry(master, show="*")
passwordB.pack()
master.resizable(width=False, height=False)
master.state('normal')
master.title("Gold Farm")
def database():
with open("accounts.pickle", "rb") as f:
return pickle.load(f)
accounts = database()
def confirm():
u, p = usernameB.get(), passwordB.get()
if accounts.get(u) == p:
print(True)
# do whatever here
else:
print(False)
# login is bad
m = messagebox.askretrycancel("Invalid input")
if not m:
master.quit()
Login = Button(master, text="Login", command=confirm)
Login.place(y=350, x=620)
Login.pack()
mainloop()
This is a rough example of how to add new users to your existing dict and pickle, you can fill in the missing logic and tidy up the display with whatever you have planned and verify input:
import pickle
from tkinter import *
master = Tk()
usernameL = Label(master, text="Username: ")
usernameL.pack()
usernameB = Entry(master)
usernameB.pack()
passwordL = Label(master, text="Password: ")
passwordL.pack()
passwordB = Entry(master, show="*")
passwordB.pack()
master.resizable(width=False, height=False)
master.state('normal')
master.title("Gold Farm")
def database():
with open("accounts.pickle", "rb") as f:
return pickle.load(f)
accounts = database()
def new():
u, p = usernameB.get(), passwordB.get()
if u in accounts:
m = messagebox.askretrycancel("Invalid","Username taken")
if not m:
master.quit()
else:
accounts[u] = p
with open("accounts.pickle","wb") as f:
pickle.dump(accounts, f)
# do whatever
def confirm():
u, p = usernameB.get(), passwordB.get()
if accounts.get(u) == p:
print(True)
# do whatever here
else:
print(False)
# do whatever when login is bad
m = messagebox.askretrycancel("Invalid input")
if not m:
master.quit()
Login = Button(master, text="Login", command=confirm)
Login.place(y=350, x=620)
Login.pack()
new_user = Button(master, text="Create acc", command=new)
new_user.pack()
mainloop()

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.

Categories