Ecco un piccolo tool desktop in Python (Tkinter) che fa esattamente quanto richiesto.
• Puoi inserire solo una delle due misure del paralume (altezza oppure larghezza).
• L’altra viene calcolata usando il rapporto aureo φ ≈ 1,618.
• Con il pulsante «Calcola base» ottieni:
1. le dimensioni della base (anch’esse in rapporto aureo);
2. un’altezza della base tale che Paralume : Base = φ.
• Tutte le dimensioni vengono automaticamente limitate ai 20 cm del piatto di stampa; se non fosse possibile, ottieni un messaggio d’errore.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk, messagebox
from math import sqrt
PHI = (1 + sqrt(5)) / 2 # 1.6180339887…
BUILD_PLATE = 20.0 # cm (20x20x20)
class LampCalculator(tk.Tk):
def __init__(self):
super().__init__()
self.title("Calcolatore lampada in rapporto aureo")
self.geometry("410x250")
self.resizable(False, False)
self.create_widgets()
# -------------------------------------------------------
# GUI
# -------------------------------------------------------
def create_widgets(self):
f = ttk.Frame(self, padding="10 10 10 10")
f.pack(expand=True, fill="both")
# Label titolo
ttk.Label(f, text="PARALUME", font=("Helvetica", 12, "bold")).grid(
column=0, row=0, columnspan=4, pady=(0, 6)
)
# Paralume - Altezza
ttk.Label(f, text="Altezza (cm):").grid(column=0, row=1, sticky="e")
self.h_shade = tk.StringVar()
ttk.Entry(f, width=10, textvariable=self.h_shade).grid(column=1, row=1, sticky="w")
# Paralume - Larghezza
ttk.Label(f, text="Larghezza (cm):").grid(column=2, row=1, sticky="e")
self.w_shade = tk.StringVar()
ttk.Entry(f, width=10, textvariable=self.w_shade).grid(column=3, row=1, sticky="w")
ttk.Button(f, text="Calcola paralume", command=self.compute_shade)\
.grid(column=0, row=2, columnspan=4, pady=(6, 12))
ttk.Separator(f, orient="horizontal").grid(column=0, row=3, columnspan=4, sticky="ew")
# BASE
ttk.Label(f, text="BASE", font=("Helvetica", 12, "bold")).grid(
column=0, row=4, columnspan=4, pady=(8, 6)
)
ttk.Label(f, text="Altezza (cm):").grid(column=0, row=5, sticky="e")
self.h_base = tk.StringVar()
ttk.Entry(f, width=10, textvariable=self.h_base, state="readonly")\
.grid(column=1, row=5, sticky="w")
ttk.Label(f, text="Larghezza (cm):").grid(column=2, row=5, sticky="e")
self.w_base = tk.StringVar()
ttk.Entry(f, width=10, textvariable=self.w_base, state="readonly")\
.grid(column=3, row=5, sticky="w")
ttk.Button(f, text="Calcola base", command=self.compute_base, state="disabled")\
.grid(column=0, row=6, columnspan=4, pady=(6, 0))
self.btn_base = f.children[list(f.children.keys())[-1]] # per abilitarlo/disabilitarlo
# Ripulire
ttk.Button(f, text="Reset", command=self.reset).grid(column=0, row=7, columnspan=4, pady=(10, 0))
# spaziatura
for child in f.winfo_children():
child.grid_configure(padx=4, pady=2)
# -------------------------------------------------------
# Logica di calcolo
# -------------------------------------------------------
def compute_shade(self):
"""Calcola la dimensione mancante del paralume."""
h = self._try_float(self.h_shade.get())
w = self._try_float(self.w_shade.get())
# Verifica input
if (h is None and w is None) or (h is not None and w is not None):
return self._error("Inserisci SOLO una delle due misure del paralume (altezza O larghezza).")
# Se è data l'altezza, calcolo la larghezza
if h is not None:
w_candidate = h * PHI # rettangolo "sdraiato"
if w_candidate > BUILD_PLATE: # prova l'orientamento opposto
w_candidate = h / PHI
w = w_candidate
# Se è data la larghezza, calcolo l'altezza
else:
h_candidate = w / PHI # rettangolo "ritto"
if h_candidate > BUILD_PLATE:
h_candidate = w * PHI
h = h_candidate
# Check dimensioni massime
if h > BUILD_PLATE or w > BUILD_PLATE:
return self._error("Impossibile rispettare il piatto di stampa 20×20 cm.\nRiduci la dimensione inserita.")
# Aggiorna campi
self.h_shade.set(f"{h:.2f}")
self.w_shade.set(f"{w:.2f}")
self.btn_base.config(state="normal") # attiva il pulsante base
self.h_base.set("")
self.w_base.set("")
# -------------------------------------------------------
def compute_base(self):
"""Calcola le dimensioni della base in rapporto aureo."""
h_shade = self._try_float(self.h_shade.get())
if h_shade is None:
return self._error("Prima calcola correttamente il paralume!")
# Altezza base tale che Paralume : Base = φ
h_base = h_shade / PHI
# Larghezza base in rapporto aureo con la sua altezza
w_base = h_base * PHI # rettangolo largo
if w_base > BUILD_PLATE:
w_base = h_base / PHI # rettangolo alto
# Se ancora non va, errore
if h_base > BUILD_PLATE or w_base > BUILD_PLATE:
return self._error("La base non rientra nei 20 cm del piatto.\nRiduci la misura del paralume.")
# Mostra risultati
self.h_base.set(f"{h_base:.2f}")
self.w_base.set(f"{w_base:.2f}")
# -------------------------------------------------------
def reset(self):
self.h_shade.set("")
self.w_shade.set("")
self.h_base.set("")
self.w_base.set("")
self.btn_base.config(state="disabled")
# -------------------------------------------------------
# Helpers
# -------------------------------------------------------
@staticmethod
def _try_float(value):
try:
return float(value) if value.strip() else None
except ValueError:
return None
def _error(self, msg):
messagebox.showerror("Errore imput", msg)
# -----------------------------------------------------------
if __name__ == "__main__":
app = LampCalculator()
app.mainloop()
Come funziona?
- Esegui lo script (
python lamp_calculator.py).
- Inserisci solo una misura del paralume (altezza oppure larghezza) e premi «Calcola paralume».
- Se la misura inserita permetterà di rientrare nel piatto di stampa, otterrai l’altra dimensione.
- Premi «Calcola base» per avere le dimensioni della base.
- «Reset» svuota tutti i campi.
Nota: Il programma tenta entrambe le orientazioni (lato lungo vs lato corto) per restare entro 20 cm, ma se ciò non è possibile comparirà un alert d’errore.