python_by_example/tkgui/tk14.py

76 lines
2.5 KiB
Python
Raw Permalink Normal View History

2023-11-19 02:48:22 -03:00
from os import getcwd as pwd
import tkinter as tk
def tk_14():
"""Change program 136 so that when a new name and gender is added to the
list box it is also written to a text file. Add another button that will
display the entire text file in the main Python shell window."""
base_path = f"{pwd()}/tkgui/imgs"
file_path = f"{pwd()}/tkgui/files/users.txt"
window = tk.Tk()
window.title("Personal Data TK")
window.geometry("590x220")
title_icon = tk.PhotoImage(file = f"{base_path}/devfzn_64x64.png")
window.iconphoto(False, title_icon)
common_bg = "dodger blue"
window["bg"] = common_bg
gender_ops = [ 'Privado', 'Masculino', 'Femenino', 'Otro' ]
lbl_info = tk.Label(text="Lista Usuarios", font="Verdana 18")
lbl_info["bg"] = common_bg
lbl_info.place(x=20, y=20, width=200, height=20)
box_name = tk.Entry()
box_name["justify"] = "left"
box_name.place(x=120, y=62, width=140, height=30)
box_name.focus()
sel_gen = tk.StringVar(window)
sel_gen.set("género")
lst_genders = tk.OptionMenu(window, sel_gen, *gender_ops)
lst_genders.place(x=275, y=60, width=100)
lst_users = tk.Listbox()
lst_users["justify"] = "center"
lst_users.place(x=400, y=50, width=150, height=140)
def add_user():
name = box_name.get()
gender = sel_gen.get()
if gender != "género" and name != '':
new_user = f"{name},{gender}"
lst_users.insert('end', new_user)
box_name.delete(0,'end')
sel_gen.set("género")
box_name.focus()
with open(file_path, '+a') as file:
file.write(new_user+"\n")
else:
lst_genders.focus()
def show_users():
print(("NOMBRE".rjust(10)).ljust(15), "GENERO".rjust(10))
with open(file_path, 'r') as file:
users = file.readlines()
for user in users:
name = user.split(',')[0]
gender = user.split(',')[1].replace('\n','')
print((name.rjust(10)).ljust(15),
(gender.ljust(10)).rjust(12))
btn_add = tk.Button(text="Agregar usuario", command=add_user)
btn_add.place(x=40, y=110, width=340, height=35)
lbl_name = tk.Message(text="NOMBRE", font="Verdana 12")
lbl_name["bg"] = common_bg
lbl_name["width"] = 70
lbl_name["justify"] = "left"
lbl_name.place(x=40, y=62, width=70, height=25)
btn_show = tk.Button(text="Mostrar en Consola", command=show_users)
btn_show.place(x=40, y=150, width=340, height=35)
window.mainloop()