USER
como experto programador, agrega funcion de autoincrementable, asi como opcion de guardar en archivo cvs al siguiente codigo: import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
def submit_appointment():
"""Handles the submission of the appointment form."""
name = name_entry.get()
phone = phone_entry.get()
date = date_entry.get()
time = time_entry.get()
reason = reason_text.get("1.0", tk.END).strip() # Get text from textarea
if not name or not phone or not date or not time or not reason:
messagebox.showerror("Error", "Please fill in all fields.")
return
# Here you would typically save the data to a database or file.
# For demonstration purposes, we'll just print it.
messagebox.showinfo("Appointment Submitted", f"Appointment submitted:\nName: {name}\nPhone: {phone}\nDate: {date}\nTime: {time}\nReason: {reason}")
#Clear the form after successful submission (optional)
name_entry.delete(0, tk.END)
phone_entry.delete(0, tk.END)
date_entry.delete(0, tk.END)
time_entry.delete(0, tk.END)
reason_text.delete("1.0", tk.END)
# Create main window
root = tk.Tk()
root.title("Medical Appointment Form")
#Labels and Entries
name_label = ttk.Label(root, text="Name:")
name_label.grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
name_entry = ttk.Entry(root)
name_entry.grid(row=0, column=1, padx=5, pady=5)
phone_label = ttk.Label(root, text="Phone:")
phone_label.grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
phone_entry = ttk.Entry(root)
phone_entry.grid(row=1, column=1, padx=5, pady=5)
date_label = ttk.Label(root, text="Date (YYYY-MM-DD):")
date_label.grid(row=2, column=0, sticky=tk.W, padx=5, pady=5)
date_entry = ttk.Entry(root)
date_entry.grid(row=2, column=1, padx=5, pady=5)
time_label = ttk.Label(root, text="Time (HH:MM):")
time_label.grid(row=3, column=0, sticky=tk.W, padx=5, pady=5)
time_entry = ttk.Entry(root)
time_entry.grid(row=3, column=1, padx=5, pady=5)
reason_label = ttk.Label(root, text="Reason for Appointment:")
reason_label.grid(row=4, column=0, sticky=tk.W, padx=5, pady=5)
reason_text = tk.Text(root, height=5, width=30)
reason_text.grid(row=4, column=1, padx=5, pady=5)
#Submit Button
submit_button = ttk.Button(root, text="Submit", command=submit_appointment)
submit_button.grid(row=5, column=1, pady=10)
root.mainloop()ASSISTANT
Para agregar una funcionalidad de ID autoincrementable y una opción para guardar las citas en un archivo CSV, podemos hacer las siguientes modificaciones al código:
1. Mantener un contador global para generar los IDs autoincrementables.
2. Utilizar el módulo `csv` de Python para guardar los datos en un archivo CSV llamado, por ejemplo, `appointments.csv`.
3. Modificar la función `submit_appointment` para usar estas nuevas funcionalidades.
Aquí tienes el código modificado:
```python
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import csv
import os
# Global variable for autoincrement ID
appointment_id = 0
# Check if the CSV file exists and create it if it doesn't
csv_file = "appointments.csv"
if not os.path.isfile(csv_file):
with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(["ID", "Name", "Phone", "Date", "Time", "Reason"]) # Write header
def submit_appointment():
"""Handles the submission of the appointment form and saves it to a CSV file."""
global appointment_id
# Read inputs
name = name_entry.get()
phone = phone_entry.get()
date = date_entry.get()
time = time_entry.get()
reason = reason_text.get("1.0", tk.END).strip() # Get text from textarea
# Validate inputs
if not name or not phone or not date or not time or not reason:
messagebox.showerror("Error", "Please fill in all fields.")
return
# Increment appointment ID
appointment_id += 1
# Save the data to the CSV file
with open(csv_file, mode='a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow([appointment_id, name, phone, date, time, reason])
# Show success message
messagebox.showinfo(
"Appointment Submitted",
f"Appointment submitted:\nID: {appointment_id}\nName: {name}\nPhone: {phone}\nDate: {date}\nTime: {time}\nReason: {reason}"
)
# Clear the form after successful submission (optional)
name_entry.delete(0, tk.END)
phone_entry.delete(0, tk.END)
date_entry.delete(0, tk.END)
time_entry.delete(0, tk.END)
reason_text.delete("1.0", tk.END)
# Create main window
root = tk.Tk()
root.title("Medical Appointment Form")
# Labels and Entries
name_label = ttk.Label(root, text="Name:")
name_label.grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
name_entry = ttk.Entry(root)
name_entry.grid(row=0, column=1, padx=5, pady=5)
phone_label = ttk.Label(root, text="Phone:")
phone_label.grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
phone_entry = ttk.Entry(root)
phone_entry.grid(row=1, column=1, padx=5, pady=5)
date_label = ttk.Label(root, text="Date (YYYY-MM-DD):")
date_label.grid(row=2, column=0, sticky=tk.W, padx=5, pady=5)
date_entry = ttk.Entry(root)
date_entry.grid(row=2, column=1, padx=5, pady=5)
time_label = ttk.Label(root, text="Time (HH:MM):")
time_label.grid(row=3, column=0, sticky=tk.W, padx=5, pady=5)
time_entry = ttk.Entry(root)
time_entry.grid(row=3, column=1, padx=5, pady=5)
reason_label = ttk.Label(root, text="Reason for Appointment:")
reason_label.grid(row=4, column=0, sticky=tk.W, padx=5, pady=5)
reason_text = tk.Text(root, height=5, width=30)
reason_text.grid(row=4, column=1, padx=5, pady=5)
# Submit Button
submit_button = ttk.Button(root, text="Submit", command=submit_appointment)
submit_button.grid(row=5, column=1, pady=10)
root.mainloop()
```
### Explicación de los cambios:
1. **ID autoincrementable (`appointment_id`)**:
- Se usa una variable global `appointment_id` que inicializamos en `0`.
- Cada vez que se llama a la función `submit_appointment`, se incrementa el valor de `appointment_id` en 1.
2. **Archivo CSV (`appointments.csv`)**:
- Si el archivo no existe, se create con un encabezado (`ID`, `Name`, `Phone`, `Date`, `Time`, `Reason`) utilizando el módulo `csv`.
- Cada vez que se envía un nuevo formulario, los datos se agregan al archivo en una nueva línea.
3. **Validaciones**:
- No cambia, pero garantiza que se llenen todos los campos antes de guardar el formulario en el archivo.
### Funcionamiento:
- Cuando el usuario llena los campos y hace clic en el botón "Submit", la información se guarda automáticamente en el archivo `appointments.csv` con un ID único asignado a cada cita.
- Esto asegura que las citas estén almacenadas de manera persistente fuera del programa.
Prueba el código y verifica cómo las citas se guardan en el archivo CSV y cómo los IDs se incrementan automáticamente.