python_by_example/tkgui/tk08.py

65 lines
2.0 KiB
Python
Raw Normal View History

2023-11-17 13:26:09 -03:00
import tkinter as tk
from os import getcwd as pwd
import csv
def tk_08():
"""Create a program that will allow the user to create a new .csv file. It
should ask them to enter the name and age of a person and then allow them
to add this to the end of the file they have just created."""
file_path = f"{pwd()}/tkgui/files/names.csv"
def add_person():
name = txt_in_name.get()
age = txt_in_age.get()
if age.isdigit():
new_person = [name, age]
with open(file_path, '+a') as file:
writer = csv.writer(file)
writer.writerow(new_person)
clear_entries()
else:
clear_entries()
def clear_entries():
txt_in_name.delete(0, 'end')
txt_in_age.delete(0, 'end')
txt_in_name.focus()
def create_csv():
open(file_path, '+w').close()
path_csv = f"Ruta: {file_path}"
lbl_file["state"] = "normal"
lbl_file.delete(0, 'end')
lbl_file.insert(0, path_csv)
lbl_file["state"] = "readonly"
window = tk.Tk()
window.title("Personas TK")
window.geometry("600x160")
lbl_name = tk.Label(text="Nombre")
lbl_name.place(x=40, y=25, width=100, height=35)
lbl_age = tk.Label(text= "Edad")
lbl_age.place(x=40, y=60, width=100, height=35)
txt_in_name = tk.Entry()
txt_in_name["justify"] = "center"
txt_in_name.place(x=140, y=25, width=150, height=35)
txt_in_name.focus()
txt_in_age = tk.Entry()
txt_in_age["justify"] = "center"
txt_in_age.place(x=140, y=60, width=150, height=35)
btn_add = tk.Button(text="Agregar a archivo", command=add_person)
btn_add.place(x=300, y=25, width=250, height=35)
btn_create = tk.Button(text="Crear archivo", command=create_csv)
btn_create.place(x=300, y=60, width=250, height=35)
lbl_file = tk.Entry()
lbl_file["state"] = "readonly"
lbl_file["justify"] = "center"
lbl_file["width"] = 580
lbl_file.place(x=10, y=110, width=580, height=35)
window.mainloop()