Ecco il codice aggiornato con tutte le modifiche richieste:
import tkinter as tk
from tkinter import ttk
import string
import json
import os
class ComputoMetrico:
def __init__(self, root):
self.root = root
self.root.title("COMPUTO METRICO 1.00")
# Massimizza la finestra
self.root.state('zoomed')
# Gestione ridimensionamento
self.root.bind('<Configure>', self.on_resize)
# Frame principale
self.main_frame = ttk.Frame(root)
self.main_frame.pack(fill=tk.BOTH, expand=True)
# Frame per le entry in alto
self.header_frame = ttk.Frame(self.main_frame)
self.header_frame.pack(fill=tk.X, padx=10, pady=10)
# Entry per Scheda e Oggetto
ttk.Label(self.header_frame, text="Scheda:").grid(row=0, column=0, sticky='w', padx=5)
self.scheda_var = tk.StringVar()
ttk.Entry(self.header_frame, textvariable=self.scheda_var, width=30).grid(row=0, column=1, sticky='w', padx=5)
ttk.Label(self.header_frame, text="Oggetto:").grid(row=0, column=2, sticky='w', padx=5)
self.oggetto_var = tk.StringVar()
ttk.Entry(self.header_frame, textvariable=self.oggetto_var, width=50).grid(row=0, column=3, sticky='w', padx=5)
# Creazione canvas con scrollbar
self.canvas = tk.Canvas(self.main_frame)
self.v_scrollbar = ttk.Scrollbar(self.main_frame, orient="vertical", command=self.canvas.yview)
self.h_scrollbar = ttk.Scrollbar(self.main_frame, orient="horizontal", command=self.canvas.xview)
# Frame interno per la tabella
self.table_frame = ttk.Frame(self.canvas)
# Configurazione scrollbar
self.canvas.configure(yscrollcommand=self.v_scrollbar.set, xscrollcommand=self.h_scrollbar.set)
# Posizionamento scrollbar
self.v_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.h_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Creazione finestra nel canvas
self.canvas.create_window((0, 0), window=self.table_frame, anchor="nw")
# Dati delle celle
self.cells = {}
self.rows = 50
self.cols = 5
# Larghezze colonne in cm
self.col_widths_cm = [11, 2, 1.5, 2, 2.5] # A, B, C, D, E
# Variabile per tenere traccia della cella attualmente selezionata
self.current_cell = None
# Creazione tabella
self.create_table()
# Frame per i pulsanti in basso
self.button_frame = ttk.Frame(self.main_frame)
self.button_frame.pack(fill=tk.X, padx=10, pady=10)
# Pulsanti P1-P5
for i in range(5):
ttk.Button(self.button_frame, text=f"P{i+1}").pack(side=tk.LEFT, padx=10)
# Bind per ridimensionamento
self.table_frame.bind("<Configure>", lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all")))
# Bind per copia/incolla
self.root.bind('<Control-c>', self.copy_cells)
self.root.bind('<Control-v>', self.paste_cells)
# Bind per navigazione con frecce e invio
self.root.bind('<Left>', self.move_left)
self.root.bind('<Right>', self.move_right)
self.root.bind('<Up>', self.move_up)
self.root.bind('<Down>', self.move_down)
self.root.bind('<Return>', self.move_down) # Invio passa alla cella sottostante
# Carica dati se esistono
self.load_data()
# Imposta i testi predefiniti nelle celle specificate
self.set_predefined_cells()
# Salva dati quando si chiude l'applicazione
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
def create_table(self):
# Stile per le celle
style = ttk.Style()
style.configure('Cell.TEntry', padding=2)
style.configure('Bold.Right.TEntry', padding=2, font=('Arial', 10, 'bold'))
style.configure('Normal.Right.TEntry', padding=2)
style.configure('Focus.TEntry', padding=2, background='yellow')
# Conversione da cm a pixel (approssimativa per un display standard)
# Assumiamo che 1 cm = circa 38 pixel su un display standard
pixels_per_cm = 38
col_widths_pixels = [w * pixels_per_cm for w in self.col_widths_cm]
# Conversione da pixel a caratteri (approssimativa)
# Assumiamo che un carattere medio sia circa 8 pixel di larghezza
col_widths_chars = [max(8, int(w / 8)) for w in col_widths_pixels]
# Header colonne (A, B, C, ...)
for col in range(self.cols):
col_name = string.ascii_uppercase[col]
label = ttk.Label(self.table_frame, text=col_name, font=('Arial', 10, 'bold'),
borderwidth=1, relief="solid", width=col_widths_chars[col], anchor='center',
background='#f0f0f0')
label.grid(row=0, column=col+1, sticky='nsew')
# Header righe (1, 2, 3, ...)
for row in range(self.rows):
label = ttk.Label(self.table_frame, text=str(row+1), font=('Arial', 10, 'bold'),
borderwidth=1, relief="solid", width=5, anchor='center',
background='#f0f0f0')
label.grid(row=row+1, column=0, sticky='nsew')
# Celle vuote
for row in range(self.rows):
for col in range(self.cols):
var = tk.StringVar()
# Determina lo stile della cella
cell_key = f"{string.ascii_uppercase[col]}{row+1}"
style_name = 'Cell.TEntry' # Stile predefinito
entry = ttk.Entry(self.table_frame, textvariable=var, width=col_widths_chars[col],
font=('Arial', 10), style=style_name, justify='right')
entry.grid(row=row+1, column=col+1, sticky='nsew', padx=1, pady=1)
# Salva riferimento alla cella
self.cells[cell_key] = {'widget': entry, 'var': var, 'row': row, 'col': col}
# Bind per selezione e focus
entry.bind('<FocusIn>', lambda e, k=cell_key: self.on_cell_focus(k))
entry.bind('<FocusOut>', lambda e, k=cell_key: self.on_cell_blur(k))
entry.bind('<Button-1>', lambda e, k=cell_key: self.on_cell_click(k, e))
# Configurazione ridimensionamento
for i in range(self.cols + 1):
self.table_frame.grid_columnconfigure(i, weight=1)
for i in range(self.rows + 1):
self.table_frame.grid_rowconfigure(i, weight=1)
# Variabili per copia/incolla
self.selected_cells = []
self.copied_data = []
def set_predefined_cells(self):
# Definizione delle celle con testo predefinito
predefined_cells = {
"A1": {"text": "A - LAVORI", "bold": True},
"A16": {"text": "Importo base d'asta", "bold": True},
"A17": {"text": "oneri per la sicurezza", "bold": True},
"A18": {"text": "TOTALE LAVORI", "bold": True},
"A20": {"text": "% IVA sui lavori", "bold": False},
"A21": {"text": "Iva sui lavori€", "bold": False},
"A22": {"text": "allacciamenti e potenziamenti", "bold": False},
"A23": {"text": "spese tecniche parcelle al lordo", "bold": False},
"A24": {"text": "Art.45", "bold": False},
"A25": {"text": "contributo ANAC e spese di pubblicazione", "bold": False},
"A26": {"text": "Imprevisti e arrotondamenti", "bold": False},
"A27": {"text": "TOTALE COMPLESSIVO", "bold": True},
"A28": {"text": "totale impegno ditta", "bold": False}
}
# Imposta il testo e lo stile per ogni cella predefinita
for cell_key, cell_info in predefined_cells.items():
if cell_key in self.cells:
self.cells[cell_key]['var'].set(cell_info["text"])
# Imposta il font in grassetto se richiesto
if cell_info["bold"]:
self.cells[cell_key]['widget'].configure(font=('Arial', 10, 'bold'))
else:
self.cells[cell_key]['widget'].configure(font=('Arial', 10))
# Allinea il testo a destra
self.cells[cell_key]['widget'].configure(justify='right')
def on_resize(self, event):
# Gestione ridimensionamento proporzionale
if hasattr(self, '_after_id'):
self.root.after_cancel(self._after_id)
self._after_id = self.root.after(100, self.resize_cells)
def resize_cells(self):
# Manteniamo le proporzioni A4 (1:√2 = 1:1.414)
width = self.root.winfo_width()
height = self.root.winfo_height()
# Non facciamo nulla qui perché abbiamo già impostato le larghezze in base ai cm
pass
def on_cell_focus(self, cell_key):
self.current_cell = cell_key
# Colora la cella di giallo quando ha il focus
self.cells[cell_key]['widget'].configure(background='yellow')
def on_cell_blur(self, cell_key):
# Ripristina il colore normale quando la cella perde il focus
self.cells[cell_key]['widget'].configure(background='white')
def on_cell_click(self, cell_key, event):
if event.state & 0x0001: # Shift premuto
if hasattr(self, 'last_clicked'):
self.select_range(self.last_clicked, cell_key)
else:
self.selected_cells = [cell_key]
else:
self.selected_cells = [cell_key]
self.last_clicked = cell_key
def move_left(self, event=None):
if self.current_cell:
col = ord(self.current_cell[0]) - ord('A')
row = int(self.current_cell[1:])
if col > 0:
new_cell = f"{chr(ord('A') + col - 1)}{row}"
if new_cell in self.cells:
self.cells[new_cell]['widget'].focus_set()
def move_right(self, event=None):
if self.current_cell:
col = ord(self.current_cell[0]) - ord('A')
row = int(self.current_cell[1:])
if col < self.cols - 1:
new_cell = f"{chr(ord('A') + col + 1)}{row}"
if new_cell in self.cells:
self.cells[new_cell]['widget'].focus_set()
def move_up(self, event=None):
if self.current_cell:
col = ord(self.current_cell[0]) - ord('A')
row = int(self.current_cell[1:])
if row > 1:
new_cell = f"{chr(ord('A') + col)}{row - 1}"
if new_cell in self.cells:
self.cells[new_cell]['widget'].focus_set()
def move_down(self, event=None):
if self.current_cell:
col = ord(self.current_cell[0]) - ord('A')
row = int(self.current_cell[1:])
if row < self.rows:
new_cell = f"{chr(ord('A') + col)}{row + 1}"
if new_cell in self.cells:
self.cells[new_cell]['widget'].focus_set()
def select_range(self, start, end):
# Seleziona un range di celle
start_col = ord(start[0]) - ord('A')
start_row = int(start[1:]) - 1
end_col = ord(end[0]) - ord('A')
end_row = int(end[1:]) - 1
self.selected_cells = []
for row in range(min(start_row, end_row), max(start_row, end_row) + 1):
for col in range(min(start_col, end_col), max(start_col, end_col) + 1):
cell_key = f"{string.ascii_uppercase[col]}{row+1}"
self.selected_cells.append(cell_key)
def copy_cells(self, event=None):
if self.selected_cells:
self.copied_data = []
for cell_key in self.selected_cells:
value = self.cells[cell_key]['var'].get()
self.copied_data.append(value)
print(f"Copiati {len(self.copied_data)} valori")
def paste_cells(self, event=None):
if self.copied_data and self.selected_cells:
# Incolla i dati nelle celle selezionate
for i, cell_key in enumerate(self.selected_cells):
if i < len(self.copied_data):
self.cells[cell_key]['var'].set(self.copied_data[i])
print(f"Incollati {len(self.copied_data)} valori