Загрузка данных



import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
import random
from datetime import datetime

db = sqlite3.connect("glucose.db")
cur = db.cursor()

cur.execute("""
CREATE TABLE IF NOT EXISTS data (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT, glucose REAL, date TEXT,
    context TEXT, feeling TEXT
)
""")
db.commit()


def save():
    try:
        name = name_entry.get()
        glucose = float(glucose_entry.get())
        context = context_box.get()
        feeling = feeling_box.get()

        if not name or not context or not feeling or glucose <= 0:
            messagebox.showerror("Ошибка", "Заполните все поля")
            return

        date = datetime.now().strftime("%d.%m.%Y %H:%M")

        cur.execute(
            "INSERT INTO data (name, glucose, date, context, feeling) "
            "VALUES (?, ?, ?, ?, ?)",
            (name, glucose, date, context, feeling)
        )
        db.commit()
        show()

    except ValueError:
        messagebox.showerror("Ошибка", "Введите число")


def auto():
    glucose_entry.delete(0, tk.END)
    glucose_entry.insert(0, str(round(random.uniform(4.0, 7.0), 1)))


def show():
    table.delete(*table.get_children())
    cur.execute("SELECT * FROM data ORDER BY id DESC")
    for row in cur.fetchall():
        table.insert("", tk.END, values=row)


window = tk.Tk()
window.title("Учёт глюкозы")
window.geometry("750x480")

tk.Label(window, text="Учёт глюкозы",
         font=("Arial", 16)).pack(pady=10)

tk.Label(window, text="Имя пользователя").pack()
name_entry = tk.Entry(window)
name_entry.pack()

tk.Label(window, text="Глюкоза (ммоль/л)").pack()
glucose_entry = tk.Entry(window)
glucose_entry.pack()

tk.Button(window, text="Автоматическое измерение",
          command=auto).pack(pady=5)

tk.Label(window, text="Контекст").pack()
context_box = ttk.Combobox(
    window, values=["Натощак", "До еды", "После еды"],
    state="readonly"
)
context_box.pack()

tk.Label(window, text="Самочувствие").pack()
feeling_box = ttk.Combobox(
    window, values=["Хорошее", "Нормальное", "Плохое"],
    state="readonly"
)
feeling_box.pack()

tk.Button(window, text="Сохранить", command=save).pack(pady=8)

table = ttk.Treeview(
    window,
    columns=("id", "name", "glucose", "date", "context", "feeling"),
    show="headings"
)

for col, title in zip(
    ("id", "name", "glucose", "date", "context", "feeling"),
    ("ID", "Имя", "Глюкоза", "Дата", "Контекст", "Самочувствие")
):
    table.heading(col, text=title)

table.pack(fill="both", expand=True, padx=5, pady=5)

show()
window.mainloop()
db.close()