Hello,
I need your help writing test functions for the following functions using pytest: add_new_user, register_user, login_verify
I am trying to test my login system program using the pytest module which is a requirement for the end-semester project. The following are functions I am having trouble testing:
Function without parameters, but rather get information from the user.
Function that appends information to a text file.
Function that reads from a text file.
Thank you in advance to the good samaritan.
1a) Python File.
def add_new_user():
"""The function enables the users to enter their information and register"""
# Gobal variables
global username
global password
global fullname
global username_entry
global password_entry
global fullname_entry
global new_user_window
# Creates another window on top of the main menu window
# for the user to enter their information.
new_user_window = Toplevel(main_window)
new_user_window.title("New User")
new_user_window.geometry("300x300")
# Create a string variable that corresponds to the user's
# username, password and full name
username = StringVar()
password = StringVar()
fullname = StringVar()
# Create "fill information" label.
label2 = Label(new_user_window, text = "Please fill in the info below", bg="gray", fg="pink")
label2.pack(fill=X, pady=20)
# Create username's label and the entry box for a user input
user_info_panel = Frame(new_user_window)
user_info_panel.pack(pady=20)
username_label=Label(user_info_panel, text="Username: ")
username_label.grid(row=0, column=0)
username_entry = Entry(user_info_panel, textvariable=username)
username_entry.grid(row=0, column=1)
# Create space between the username and password
Label(user_info_panel, text="").grid(row=1)
# Create password's label and the entry box for a user input
password_label = Label(user_info_panel, text="Password: ")
password_label.grid(row=2, column=0)
password_entry = Entry(user_info_panel, textvariable=password)
password_entry.grid(row=2, column=1)
# Create space between password and full name
Label(user_info_panel, text="").grid(row=3)
# Create full name's label and an entry box for the user input
fullname_label = Label(user_info_panel, text="Full name: ")
fullname_label.grid(row=4, column=0)
fullname_entry = Entry(user_info_panel, textvariable=fullname)
fullname_entry.grid(row=4, column=1)
# Create registration button for the user to their information.
register_btn = Button(new_user_window, text="Register", command=register_user)
register_btn.pack()
b) Test file
def test_add_new_user():
"""Verify that the add_new_user function works correctly.
Parameters: none
Return: nothing
"""
assert add_new_user("username") == "Fred69_Coder"
assert add_new_user("password") == "#123kitoVu"
assert add_new_user("fullname") == "Fred Okorio"
2a) Python file
def register_user():
"""The function writes the user's confidential information in a text file"""
# Initialize the False boolean variable
registered = False
# Get the information typed by the user in the entry boxes.
username_text = username.get()
password_text = password.get()
name_text = fullname.get()
try:
# Create the credentials text file and append the new user information
# in the already existing file.
with open("credentials.txt", "a") as credentials:
# Open the credential text file for reading and store a reference
# to the opened file in a variable named text_file.
with open("credentials.txt", "r") as text_file:
# Read the contents of the text
# file one line at a time.
for line in text_file:
# Split the data in line variable and store the split
# data in the login_info variable.
login_info = line.split()
# From all the information in the data base extract
# username information.
if username_text == login_info[1]:
registered = True
# If the user is already registered
if registered:
# Clear the user entry boxes
username_entry.delete(0, END)
password_entry.delete(0, END)
fullname_entry.delete(0, END)
# For debugging purpose
print("user already exist")
# Window for a failed login process.
failed_registration_window = Toplevel(new_user_window)
failed_registration_window.geometry("200x200")
failed_registration_window.title("warning!")
Label(failed_registration_window, text="user already exists.",
bg="gray", fg="pink").pack(fill=X, pady=20)
# Ok button exits the window
ok_btn = Button(failed_registration_window, text="Please login",
width="20",command=lambda:failed_registration_window.destroy())
ok_btn.pack(pady=20)
else:
credentials.write("Username: "+ username_text + " " + "Password: " + password_text + " " +"Name: "+ name_text + "\n")
# Clear the user entry boxes.
username_entry.delete(0, END)
password_entry.delete(0, END)
fullname_entry.delete(0, END)
# Window for a successful login process.
successful_registration_window = Toplevel(new_user_window)
successful_registration_window.geometry("200x200")
successful_registration_window.title("Success!")
Label(successful_registration_window, text="Sucessfully
Registered!", bg="gray", fg="pink").pack(fill=X, pady=20)
ok_btn = Button(successful_registration_window, text="OK", width="20", command = lambda:successful_registration_window.destroy())
ok_btn.pack(pady=20)
except FileNotFoundError as not_found_err: print(not_found_err)
except PermissionError as perm_err: print(perm_err)
b) Test file
def test_register_user():
"""Verify that the register_user function works correctly.
Parameters: none
Return: nothing
"""
3a) Python file
def login_verify():
try:
user = username_verify.get()
password = password_verify.get()
login = False
# Open the credential text file for reading and store a reference
# to the opened file in a variable named text_file.
with open("credentials.txt", "r") as text_file:
# Read the contents of the text
# file one line at a time.
for line in text_file:
login_info = line.split()
if user == login_info[1] and password == login_info[3]:
login = True
if login:
label1 = Label(login_window, text = "You've logged in successfully", fg="green")
label1.pack()
else:
failed_login_window = Toplevel(login_window)
failed_login_window.geometry("200x200")
failed_login_window.title("Warning!")
Label(failed_login_window, text="Invalid username. Please register", bg="gray", fg="pink").pack(fill=X, pady=20)
ok_btn = Button(failed_login_window, text="OK", width="20", command= lambda:failed_login_window.destroy())
ok_btn.pack(pady=20)
except IndexError as index_err:
print(index_err)
except FileNotFoundError as not_found_err:
print(not_found_err)
except PermissionError as perm_err:
print(perm_err)
b) Test file
def test_login_verify():
"""Verify that the login_verify function works correctly.
Parameters: none
Return: nothing
"""
Related
I created a password manager app and I need to encrypt and decrypt the passwords when I use my decrypted variable its shows me that the variable is not defined and I defined it earlier in the code I cant even run the code because of that error If Someone knows how to fix it please help me
here's the link for the code
#My coding skills got you climbing hills
from tkinter import *
import customtkinter
import os
import random
import pyperclip as pc
from tkinter import messagebox as mb
from cryptography.fernet import Fernet
global encrypted
customtkinter.set_appearance_mode("Light")
window=customtkinter.CTk()
# Making all the widgets for thte password saver
window.title("Password saver for me")
window.geometry("750x420")
# Logic (The hard part)
#----------------------------------------------------
def main_func():
#Add Passwords Function
def add():
for i in window.winfo_children():
i.destroy()
password=customtkinter.CTkEntry(window,
width=230
,border_width=0.5
,placeholder_text="Password"
,placeholder_text_color="Silver")
user=customtkinter.CTkEntry(window,
width=230,
border_width=0.5
,placeholder_text="User"
,placeholder_text_color="Silver")
platform_=customtkinter.CTkEntry(window,
width=490,
border_width=0.5
,placeholder_text="Platform"
,placeholder_text_color="Silver")
password.place(x=450,y=35) #I wasn't able to calculate this by myself
user.place(x=192,y=35)
platform_.place(x=192,y=70)
main_func()
def logic():
#Opens the file and writes the user information inside it
#Guardian
if platform_.get() == "" or user.get() == "" or password.get() == "":
mb.showerror("WRONG INPUT","Please Make sure to enter all the fields \nIf you don't have a username/password Enter \'None\'")
return
file = open("pass.txt","a")
write_platform_=file.write("Platform: "+platform_.get()+" | ")
write_email=file.write("Username/Email: "+user.get()+" | ")
write_password=file.write("Password: "+password.get()+"\n")
file.close()
key = Fernet.generate_key()
with open("MyKey.key","wb") as mykey:
mykey.write(key)
############################################ddddddddddddddddddddddddddddddddddddddddddd
with open("MyKey.key","rb") as mykey:
key = mykey.read()
f = Fernet(key)
with open("pass.txt","rb") as original_file:
original = original_file.read()
encrypted = f.encrypt(original)
#########################################3
with open("enc_passwords.txt","wb") as encrypted_file:
encrypted_file.write(encrypted)
f = Fernet(key)
with open("enc_passwords.txt","rb") as encrypted_file:
encrypted=encrypted_file.read()
decrypted=f.decrypt(encrypted)
file=open("pass.txt","wb")
file.write(encrypted)
#Clear Fields
def clear_field():
for i in window.winfo_children():
i.destroy()
add()
def generate_password():
for i in range(12):
a = random.choice("Q!w!E!r!T!y!U!i!O!p!A!s!D!fGhJkLzXcVbNm1234567890")
password.insert(i,a)
pc.copy(password.get())
save=customtkinter.CTkButton(window,text="Save",
command=logic
,fg_color='red',
hover_color="white"
,width=490).place(x=192,y=105)
first_generate_button=customtkinter.CTkButton(window
,width=490
,text="Generate Random Password"
,fg_color="red"
,hover_color="white"
,command=generate_password).place(x=192,y=105+35)
clear_fields=customtkinter.CTkButton(window
,width=490
,text="Clear Fields"
,fg_color="Red"
,hover_color="white"
,command=clear_field).place(x=192,y=105+70)
#--------------------------------------------------------------------------------
def generate():
for i in window.winfo_children():
i.destroy()
main_func()
password_label2=customtkinter.CTkLabel(window,
text="New Password")
password_label2.place(x=191,y=65)
rand_password=customtkinter.CTkEntry(window,
border_width=0.5)
rand_password.place(x=192,y=150-65)
for i in range(12):
a = random.choice("QwErTyUiOpAsDfGhJkLzXcVbNm1234567890")
rand_password.insert(i,a)
pc.copy(rand_password.get())
#---------------------------------------------------------------
#----------------------------------------------------------------
#----------------------------------------------------------------------
#Not finished Need to add encryption
def add_passport():
for i in window.winfo_children():
i.destroy()
name=customtkinter.CTkEntry(window
,placeholder_text="Enter Surname"
,placeholder_text_color="Silver")
passport_no=customtkinter.CTkEntry(window
,placeholder_text="Enter Given name",
placeholder_text_color="Silver")
nation=customtkinter.CTkEntry(window
,placeholder_text="Nationality"
,placeholder_text_color="Silver")
date_of_birth=customtkinter.CTkEntry(window
,placeholder_text="Date of birth"
,placeholder_text_color="Silver")
date_of_issue=customtkinter.CTkEntry(window
,placeholder_text="Date of issue"
,placeholder_text_color="Silver")
authority=customtkinter.CTkEntry(window
,placeholder_text="Authority"
,placeholder_text_color="Silver")
name.place(x=200,y=35)
passport_no.place(x=370,y=35)
nation.place(x=540,y=35)
date_of_birth.place(x=200,y=70)
date_of_issue.place(x=370,y=70)
authority.place(x=540,y=70)
# The space between x + 170 and y supposed to be + 35
main_func()
# platform_: Iphone | Username/Email: Nitay | Password: pro
#All the Buttons
#Saved button
def saved():
file1 = open("pass.txt","rb")
new_window=customtkinter.CTk()
saved_passwords=customtkinter.CTkLabel(new_window,text=decrypted)
saved_passwords.pack()
new_window.mainloop()
return
saved=customtkinter.CTkButton(window,command=saved
,fg_color="red",
hover_color="white",
text="Saved Passwords").place(x=1,y=0)
# Generate password button
#------------------------------------------------------------------------
generate_button=customtkinter.CTkButton(window,text="Generate Password",
command=generate,height=28,
fg_color="red",
hover_color="white").place(x=1,y=35)
#------------------------------------------------------------------------
#Save button
#-------------------------------------------------
add_password=customtkinter.CTkButton(window
,text="Add Password"
,fg_color="red"
,hover_color="white"
,command=add).place(x=1,y=70)
#-------------------------------------------------
#Add Password Button
add_passports=customtkinter.CTkButton(window,text="Add Passport"
,fg_color="red"
,hover_color="white"
,command=add_passport).place(x=1,y=105)
#Main Loop
main_func()
window.mainloop()
from tkinter import *
from tkinter import messagebox
w=Tk()
w.geometry('350x500')
w.title('Sunset Panel')
w.resizable(0,0)
#Making gradient frame
j=0
r=10
for i in range(100):
c=str(222222+r)
Frame(w,width=10,height=500,bg="#"+c).place(x=j,y=0)
j=j+10
r=r+1
Frame(w,width=250,height=400,bg='white').place(x=50,y=50)
l1=Label(w,text='Username',bg='white')
l=('Consolas',13)
l1.config(font=l)
l1.place(x=80,y=200)
#e1 entry for username entry
e1=Entry(w,width=20,border=0)
l=('Consolas',13)
e1.config(font=l)
e1.place(x=80,y=230)
#e2 entry for password entry
e2=Entry(w,width=20,border=0,show='*')
e2.config(font=l)
e2.place(x=80,y=310)
l2=Label(w,text='Password',bg='white')
l=('Consolas',13)
l2.config(font=l)
l2.place(x=80,y=280)
###lineframe on entry
Frame(w,width=180,height=2,bg='#141414').place(x=80,y=332)
Frame(w,width=180,height=2,bg='#141414').place(x=80,y=252)
from PIL import ImageTk,Image
imagea=Image.open("log.png")
imageb= ImageTk.PhotoImage(imagea)
label1 = Label(image=imageb,
border=0,
justify=CENTER)
label1.place(x=115, y=50)
#Command
def cmd():
db = open("Data.txt", "r")
Username = e1
Password = e2
if Username == e1:
d = []
f = []
for i in db:
a,b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d, f))
if e1.get() == data[Username] and e2.get() == data[Password]:
messagebox.showinfo("Login success", "Welcome")
q=Tk()
q.mainloop()
else:
messagebox.showwarning("Login failed dumb ass","Try again goofy")
#Button_with hover effect
def bttn(x,y,text,ecolor,lcolor):
def on_entera(e):
myButton1['background'] = ecolor #ffcc66
myButton1['foreground']= lcolor #000d33
def on_leavea(e):
myButton1['background'] = lcolor
myButton1['foreground']= ecolor
myButton1 = Button(w,text=text,
width=20,
height=2,
fg=ecolor,
border=0,
bg=lcolor,
activeforeground=lcolor,
activebackground=ecolor,
command=cmd)
myButton1.bind("<Enter>", on_entera)
myButton1.bind("<Leave>", on_leavea)
myButton1.place(x=x,y=y)
bttn(100,375,'L O G I N','white','#994422')
w.mainloop()
my error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\ezneu\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\ezneu\OneDrive\Desktop\login\login.py", line 80, in cmd
if e1.get() == data[Username] and e2.get() == data[Password]:
KeyError: <tkinter.Entry object .!entry>
sorry for the dumb question ive been at this all day and cant seem to figure out what the problem is I sent the entire code above if someone can correct! I keep getting the same " KeyError: <tkinter.Entry object .!entry>" no clue what this means but I even watched a tutorial and my code was almost the same as the person in the tut yet there worked perfect please help!
Since Username is a reference to an Entry widget and data is a dictionary with string as the keys, so data[Username] will raise the exception.
Your checking should test whether e1.get() is a key in data and e2.get() should be equal to data[e1.get()].
Below is the suggested modification of cmd():
def cmd():
username = e1.get().strip()
password = e2.get().strip()
# both username and password have been input?
if username and password:
# load the credentials as a dictionary
with open("Data.txt") as db:
data = {}
for i in db:
a, b = i.split(", ")
data[a] = b.strip()
# check username and password
if username in data and data[username] == password:
messagebox.showinfo("Login Success", "Welcome")
# do whatever you want if login successful
else:
messagebox.showwarning("Login Failed", "Try again")
else:
messagebox.showwarning("Invalid", "Please enter both username and password")
https://realpython.com/python-keyerror/ :
A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary ( in your case data ).
Here an example of content of the file 'Data.txt':
adam, a
bogdan, b
cicero, c
daniel, d
Below a making sense code of cmd() running without the error message:
def cmd():
db = open("Data.txt", "r")
d = []
f = []
for i in db.readlines():
print (i)
a, b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d, f))
print(data)
try:
if data[e1.get()] == e2.get():
messagebox.showinfo("Login success", "Welcome")
q=Tk()
q.mainloop()
else:
messagebox.showwarning("Wrong password entered", "Try again")
except KeyError:
messagebox.showwarning("Login failed dumb ass","Try again goofy")
And here entire code with the gradient frame which looks like it should:
from tkinter import *
w=Tk()
w.geometry('350x500')
w.title('Sunset Panel')
w.resizable(0,0)
#Making gradient frame
j=0; r=10
for _ in range(35):
c=str(f'{155-r:02x}{255-r:02x}{155-r:02x}')
print(c,end='|')
Frame(w,width=10,height=500,bg="#"+c).place(x=j,y=0)
j=j+10
r=r+3
Frame(w,width=250,height=400,bg='white').place(x=50,y=50)
l1=Label(w,text='Username',bg='white')
l=('Consolas',13)
l1.config(font=l)
l1.place(x=80,y=200)
#e1 entry for username entry
e1=Entry(w,width=13,border=0)
l=('Consolas',13)
e1.config(font=l)
e1.place(x=80,y=230)
#e2 entry for password entry
e2=Entry(w,width=13,border=0,show='*')
e2.config(font=l)
e2.place(x=80,y=310)
l2=Label(w,text='Password',bg='white')
l=('Consolas',13)
l2.config(font=l)
l2.place(x=80,y=280)
###lineframe on entry
Frame(w,width=180,height=2,bg='#141414').place(x=80,y=332)
Frame(w,width=180,height=2,bg='#141414').place(x=80,y=252)
from PIL import ImageTk,Image
imagea=Image.open("log.png")
imageb= ImageTk.PhotoImage(imagea)
label1 = Label(image=imageb, border=0, justify=CENTER)
label1.place(x=115, y=50)
#Command
def cmd():
db = open("Data.txt", "r")
d = []
f = []
for i in db.readlines():
print (i)
a, b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d, f))
print(data)
try:
if data[e1.get()] == e2.get():
messagebox.showinfo("Login success", "Welcome")
q=Tk()
q.mainloop()
else:
messagebox.showwarning("Wrong password entered", "Try again")
except KeyError:
messagebox.showwarning("Login failed dumb ass","Try again goofy")
#Button_with hover effect
def bttn(x,y,text,ecolor,lcolor):
def on_entera(e):
myButton1['background'] = ecolor #ffcc66
myButton1['foreground']= lcolor #000d33
def on_leavea(e):
myButton1['background'] = lcolor
myButton1['foreground']= ecolor
myButton1 = Button(w,text=text,
width=20,
height=2,
fg=ecolor,
border=0,
bg=lcolor,
activeforeground=lcolor,
activebackground=ecolor,
command=cmd)
myButton1.bind("<Enter>", on_entera)
myButton1.bind("<Leave>", on_leavea)
myButton1.place(x=x,y=y)
bttn(100,375,'L O G I N','white','#994422')
w.mainloop()
Got an error of: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied when using socket with tkinter on login between server and client
Server :
import socket
import pickle
import datetime
# Socket settings
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket setting
my_socket.bind(('0.0.0.0', 1024)) # binding the server ip
my_socket.listen(10) # how much people can join the server
client_socket, client_address = my_socket.accept() # accepting the people if the server is available
print("Server Open") # prints that the server is open
# Functions
def get_users():
# get from the login_users.txt all users & passwords
# format in file - username|password
logs = []
with open('login_users.txt', 'r') as f:
for line in f:
cur = line.strip('\n\r')
cur = cur.split("|")
logs.append(cur)
f.close()
return logs
def get_rank(user):
# get from the ranks.txt all users & passwords
# format in file - username|password
ranks = []
with open('ranks.txt', 'r') as f:
for line in f:
cur = line.strip('\n\r')
cur = cur.split("|")
ranks.append(cur)
f.close()
for r in ranks:
if r[0] == user:
return r[1]
def add_to_logs(user, line):
# add attempt to record (logs_.txt)
now = datetime.datetime.now()
with open('logs_.txt', 'a') as f:
f.write(line + " " + str(now) + "\n")
f.close()
def user_exist(user):
for log in logs:
if log[0] == user:
return True
def check(user, password):
# check the password that the user typed
# if there are 3 failed tried disable the login button
global logs
global atmp
global null_state
global login_state
global logged_user
global status
# get text from boxes:
user = user.get()
password = password.get()
print("user: ", user)
print("pass: ", password)
# add attempt to logs_ file
add_to_logs(user, f"{user} has tried to log in.")
atmp += 1
if user_exist(user):
null_state = False
for log in logs:
if log[0] == user and log[1] == password:
# pop up login succeed
login_state = True
logged_user = user
status = True
if __name__ == '__main__':
btpressed = pickle.loads(my_socket.recv(1024))
if btpressed:
client_socket.send(pickle.dumps([status]))
username, password = pickle.loads(my_socket.recv(1024)) # Getting data from the server
status = check(username, password)
print(status)
client:
import socket
import pickle
import tkinter as tk
import tkinter.messagebox as mb
import tkinter.font as tkFont
user_send = "nothing"
pass_send = "nothing"
# Socket settings
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # setting the socket
my_socket.connect(('127.0.0.1', 1024)) # joining the server
print("Connected to the server successfully!")
def check_null(user, password):
global null_state
# check for the username and password in the file:
if user == "" or password == "" or user == "" and password == "":
null_state = True
fail_msg = "Please make sure you have entered username and password in both fields!"
mb.showinfo(title="Enter username and password", message=fail_msg)
#def display_system():
#root1.title("Secure4U")
#root1.geometry("1200x600")
#fontStyle = tkFont.Font(family="Lucida Grande", size=20)
#show_user_logged = tk.Label(root1, text="Hello " + logged_user + ",", font=fontStyle)
#show_user_logged.pack(side="top", anchor="nw")
#user_rank =
#show_user_rank = tk.Label(root1, text="Rank: " + str(user_rank), font=fontStyle)
#show_user_rank.pack(side="top", anchor="nw")
#root1.mainloop() # run tkinter display
def display_login():
global log_button
# initiate and display all objects on screen
root.title("Secure4U Login")
root.geometry("450x250")
fontStyle = tkFont.Font(family="Lucida Grande", size=20)
# user name
user_label = tk.Label(root, text="Username:", font=fontStyle)
# user_box = tk.Text(root, bg="grey", height=1, width=20, font=fontStyle)
user_box = tk.Entry(root, bg="grey", font=fontStyle)
user_label.pack()
user_box.pack()
# password
pass_label = tk.Label(root, text="Password:", font=fontStyle)
# pass_box = tk.Text(root, bg="grey", font=fontStyle)
pass_box = tk.Entry(root, bg="grey", font=fontStyle, show="*")
pass_label.pack()
pass_box.pack()
# login button
log_button = tk.Button(root, text='Login', height=2, width=20, command=lambda:(button_pressed()))
log_button.pack()
user_send = user_box
pass_send = pass_box
root.mainloop() # run tkinter display
def button_pressed():
BtPressed = True
if __name__ == '__main__':
global BtPressed
BtPressed = False
status = False
my_socket.send(pickle.dumps([BtPressed]))
if not status:
null_state = False # checks if the user entered null data on one or both of the fields
root = tk.Tk()
display_login()
if BtPressed:
my_socket.send(pickle.dumps([user_send, pass_send])) # Sending data to the server
status = pickle.loads(my_socket.recv(1024)) # Getting data from the server
# success_msg = f"Hello {logged_user}, you logged in successfully!"
# mb.showinfo(title="login succeed!", message=success_msg)
I don't know what it happened and I tried everything, please help me if you can
Thank you :)
so I am making a program on tkinter that gets a response from a server and depending on the answer, it will change the background color, to either green for success or red for error, the problem is that I realized that when running the code, the windows.after() method doesn't wait till is done to continue and when I do the request for the server, it have to do it three times to check if the response is correct, and it is suppossed to change the window background color each time, but it is only doing it one time. And not only the background color changing fails, also I want to change a label's text when it is doing the request,but it does it really quick and I'm not able to diferentiate the changes, so the question is: how can I
How can I make the program wait until one line finishes running to go to the next one and not everything happens at the same time and so fast?
Here is a piece of my code, I removed the request part because I'm trying to solve this problem first:
# import gpiozero
# import picamera
import json
import requests
import tkinter as tk
with open("config.json") as file:
config = json.load(file)
ENDPOINT = config["ENDPOINT"]
USUARIO = config["USUARIO"]
ESTACION = config["ESTACION"]
TIEMPO_ESPERA = config["TIEMPO_ESPERA"]
PIN_RELE = config["PIN_RELE"]
PATH_SALIDA = ENDPOINT + "Salida.getTicket/" + ESTACION + "/" + USUARIO + "/"
barcode = ""
# RELAY = gpiozero.OutputDevice(PIN_RELE, active_high=True, initial_value=False)
# CAMERA = picamera.PiCamera()
def check_scan_barcode(event=None):
info_label.config(text = "Wait...")
barcode = barcode_entry.get()
barcode_entry.delete(0, "end")
for i in range(3):
response = get_request(ENDPOINT + barcode)
if response["data"] == "True":
success()
open_barrier()
else:
error()
info_label.config(text = "Scan barcode")
def get_request(url):
response = requests.get(url)
response.raise_for_status()
response = response.json()
return response
def normal():
window.configure(bg="white")
info_label.configure(bg="white")
def success():
window.configure(bg="green")
info_label.configure(bg="green")
window.after(1000, normal)
def error():
window.configure(bg="red")
info_label.configure(bg="red")
window.after(1000, normal)
def open_barrier(barcode):
# CAMERA.capture(f"/home/pi/Pictures{barcode}.jpg")
# RELAY.on()
# window.after(TIEMPO_ESPERA, RELAY.off)
pass
window = tk.Tk()
# window.attributes('-fullscreen', True)
info_label = tk.Label(window, text= "Scan barcode.", font=("Arial", 40))
info_label.pack()
barcode_entry = tk.Entry(window, width=50)
barcode_entry.bind('<Return>', check_scan_barcode)
barcode_entry.pack(expand=True)
barcode_entry.focus()
window.mainloop()
I want to print a message on the UI when the user wishes to exit.
This is a part of code relevant to it
if word in quit_words:
user_to_quit = True
Print = "Pleasure serving you!"
print_bot_reply(Print)
time.sleep(5)
root.destroy()
The print bot_reply function is as follows:
def print_bot_reply(response):
response = "\nKalpana: " + str(response)
label = Label(frame,text = response,bg="#b6efb1", borderwidth=5, relief="raised")
label.pack(anchor = "w")
The window is closing after 5 seconds, as desired but not displaying the message.
Please point me the mistake or suggest some other method to do this
Thanks!