-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1860 lines (1536 loc) · 67.1 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Supplement Tracker Application
This module contains the main Supplement Tracker application built using Tkinter.
It allows users to track their supplement inventory, calculate costs, and more.
"""
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
from datetime import datetime
import webbrowser
from typing import List, Dict
import sys
import os
import logging
import shutil
import gzip
import time
# Set up logging
logging.basicConfig(
filename='supplement_tracker.log',
level=logging.ERROR,
format='%(asctime)s - %(levelname)s - %(message)s'
)
class BackupManager:
"""
Manages the backup system for supplement data files.
This class handles creating, managing, and restoring backups of supplement data files.
It supports automatic and manual backups, rotation of old backups, and metadata tracking.
"""
def __init__(self, settings, max_backups=5, backup_dir='./backup'):
"""
Initialize the BackupManager.
Args:
settings (dict): The application settings dictionary.
max_backups (int): Maximum number of backups to keep (default: 5).
backup_dir (str): Directory to store backups (default: './backup').
"""
self.settings = settings
# Initialize backup settings with defaults if not present
if 'backup' not in self.settings:
self.settings['backup'] = {
'max_backups': max_backups,
'backup_dir': backup_dir,
'compression_enabled': False,
'min_backup_interval_minutes': 60
}
self.backup_settings = self.settings['backup']
self.last_backup_time = 0
self.backup_index_file = os.path.join(self.backup_settings['backup_dir'], 'backup_index.json')
self.backup_index = self._load_backup_index()
# Ensure backup directory exists
self.ensure_backup_directory()
def ensure_backup_directory(self):
"""Create the backup directory if it doesn't exist."""
try:
os.makedirs(self.backup_settings['backup_dir'], exist_ok=True)
return True
except Exception as e:
logging.error(f"Failed to create backup directory: {str(e)}", exc_info=True)
return False
def _load_backup_index(self):
"""Load the backup index file or create a new one if it doesn't exist."""
if os.path.exists(self.backup_index_file):
try:
with open(self.backup_index_file, 'r') as f:
return json.load(f)
except Exception as e:
logging.error(f"Failed to load backup index: {str(e)}", exc_info=True)
return {'backups': []}
return {'backups': []}
def _save_backup_index(self):
"""Save the backup index to file."""
try:
with open(self.backup_index_file, 'w') as f:
json.dump(self.backup_index, f, indent=4)
return True
except Exception as e:
logging.error(f"Failed to save backup index: {str(e)}", exc_info=True)
return False
def generate_backup_filename(self, source_file):
"""
Generate a backup filename based on the current date and time.
Args:
source_file (str): The original file path.
Returns:
str: The generated backup filename.
"""
# Get the base filename without path
base_filename = os.path.basename(source_file)
name, ext = os.path.splitext(base_filename)
# Generate timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"backup_{timestamp}{ext}"
# Check for collisions
counter = 1
full_path = os.path.join(self.backup_settings['backup_dir'], backup_name)
while os.path.exists(full_path):
backup_name = f"backup_{timestamp}_{counter}{ext}"
full_path = os.path.join(self.backup_settings['backup_dir'], backup_name)
counter += 1
return full_path
def should_create_backup(self, is_auto_save=True):
"""
Determine if a backup should be created based on settings and timing.
Args:
is_auto_save (bool): Whether this is an automatic save (default: True).
Returns:
bool: True if a backup should be created, False otherwise.
"""
# Always create backup for manual saves
if not is_auto_save:
return True
# Check time since last backup
current_time = time.time()
min_interval = self.backup_settings['min_backup_interval_minutes'] * 60
if current_time - self.last_backup_time >= min_interval:
return True
return False
def create_backup(self, source_file, is_auto_save=True):
"""
Create a backup of the specified file.
Args:
source_file (str): The path to the file to back up.
is_auto_save (bool): Whether this is an automatic save (default: True).
Returns:
str: The path to the created backup file, or None if backup failed.
"""
if not os.path.exists(source_file):
logging.error(f"Source file does not exist: {source_file}")
return None
# Check if we should create a backup
if not self.should_create_backup(is_auto_save):
return None
try:
# Generate backup filename
backup_file = self.generate_backup_filename(source_file)
# Copy the file
if self.backup_settings.get('compression_enabled', False):
with open(source_file, 'rb') as f_in:
with gzip.open(f"{backup_file}.gz", 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
backup_file = f"{backup_file}.gz"
else:
shutil.copy2(source_file, backup_file)
# Update backup index
file_size = os.path.getsize(backup_file)
backup_info = {
'filename': os.path.basename(backup_file),
'original_file': source_file,
'timestamp': datetime.now().isoformat(),
'is_auto': is_auto_save,
'size': file_size
}
self.backup_index['backups'].append(backup_info)
self._save_backup_index()
# Update last backup time
self.last_backup_time = time.time()
# Clean up old backups
self.cleanup_old_backups()
logging.info(f"Created backup: {backup_file}")
return backup_file
except Exception as e:
logging.error(f"Failed to create backup: {str(e)}", exc_info=True)
return None
def list_backups(self):
"""
List all available backups.
Returns:
list: A list of backup information dictionaries.
"""
return sorted(self.backup_index['backups'],
key=lambda x: x['timestamp'],
reverse=True)
def cleanup_old_backups(self):
"""
Remove old backups to stay within the maximum limit.
Returns:
int: Number of backups removed.
"""
backups = self.list_backups()
max_backups = self.backup_settings['max_backups']
if len(backups) <= max_backups:
return 0
removed = 0
for backup in backups[max_backups:]:
try:
backup_path = os.path.join(self.backup_settings['backup_dir'], backup['filename'])
if os.path.exists(backup_path):
os.remove(backup_path)
removed += 1
except Exception as e:
logging.error(f"Failed to remove old backup: {str(e)}", exc_info=True)
# Update the index
self.backup_index['backups'] = backups[:max_backups]
self._save_backup_index()
return removed
def restore_from_backup(self, backup_file, target_file):
"""
Restore a file from a backup.
Args:
backup_file (str): The backup file to restore from.
target_file (str): The target file to restore to.
Returns:
bool: True if restoration was successful, False otherwise.
"""
try:
backup_path = os.path.join(self.backup_settings['backup_dir'], backup_file)
if not os.path.exists(backup_path):
logging.error(f"Backup file does not exist: {backup_path}")
return False
# Handle compressed backups
if backup_path.endswith('.gz'):
with gzip.open(backup_path, 'rb') as f_in:
with open(target_file, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
else:
shutil.copy2(backup_path, target_file)
logging.info(f"Restored from backup: {backup_file} to {target_file}")
return True
except Exception as e:
logging.error(f"Failed to restore from backup: {str(e)}", exc_info=True)
return False
def load_settings():
"""Load user settings from settings.json."""
default_settings = {
"theme": "dark",
"last_file": None,
"backup": {
"max_backups": 5,
"backup_dir": "./backup",
"compression_enabled": False,
"min_backup_interval_minutes": 60
}
}
try:
if os.path.exists('settings.json'):
with open('settings.json', 'r') as f:
settings = json.load(f)
# Ensure backup settings exist
if 'backup' not in settings:
settings['backup'] = default_settings['backup']
return settings
return default_settings
except Exception as e:
logging.error("Failed to load settings", exc_info=True)
return default_settings
def save_settings(settings):
"""Save user settings to settings.json."""
try:
with open('settings.json', 'w') as f:
json.dump(settings, f, indent=4)
except Exception as e:
logging.error("Failed to save settings", exc_info=True)
def handle_error(error, user_message=None):
"""Centralized error handling function."""
logging.error(str(error), exc_info=True)
if user_message:
messagebox.showerror("Error", user_message)
else:
messagebox.showerror("Error", str(error))
class ModernTheme:
"""
A modern theme for Tkinter applications.
This class provides a customizable dark/light theme with a modern look and feel.
It can be applied to Tkinter and ttk widgets.
"""
def __init__(self, is_dark=True):
"""
Initialize the ModernTheme.
Args:
is_dark (bool): Whether to use a dark theme (default: True).
"""
self.settings = load_settings()
self.is_dark = self.settings.get("theme", "dark") == "dark" if is_dark is None else is_dark
self.update_colors()
self.style = None # Will be set in apply()
self.fonts = {
'heading': ('Segoe UI', 11, 'bold'),
'body': ('Segoe UI', 10),
'small': ('Segoe UI', 9)
}
def update_colors(self):
"""Update the theme colors based on the current mode (dark/light)."""
if self.is_dark:
self.colors = {
'primary': '#2196F3', # Material Blue
'secondary': '#FFC107', # Material Amber
'background': '#1E1E1E', # Dark background
'surface': '#2D2D2D', # Dark surface
'text': '#FFFFFF', # White text
'text_secondary': '#AAAAAA', # Light gray text
'hover': '#3D3D3D', # Slightly lighter than surface
}
else:
self.colors = {
'primary': '#2196F3', # Material Blue
'secondary': '#FFC107', # Material Amber
'background': '#FFFFFF', # White background
'surface': '#F5F5F5', # Light surface
'text': '#212121', # Dark text
'text_secondary': '#757575', # Gray text
'hover': '#E0E0E0', # Light gray hover
}
def apply(self, root):
"""
Apply the theme to a Tkinter application.
Args:
root (Union[tk.Tk, tk.Toplevel]): The root window of the application.
Returns:
ttk.Style: The style object with the applied theme.
"""
style = ttk.Style()
style.theme_use('default')
# Configure common colors and fonts
style.configure('.',
background=self.colors['background'],
foreground=self.colors['text'],
fieldbackground=self.colors['surface'],
font=self.fonts['body']
)
# Configure specific widget styles
style.configure('TButton',
padding=5,
relief='flat',
background=self.colors['surface'],
foreground=self.colors['text']
)
style.map('TButton',
relief=[('pressed', 'flat')],
background=[
('pressed', self.colors['primary']),
('active', self.colors['hover']),
('!active', self.colors['surface'])
],
foreground=[('pressed', '#FFFFFF')]
)
# Theme toggle button
style.configure('Toggle.TButton',
padding=5,
relief='flat',
background=self.colors['surface']
)
style.map('Toggle.TButton',
relief=[('pressed', 'flat')],
background=[
('pressed', self.colors['secondary']),
('active', self.colors['hover'])
]
)
# Entry fields
style.configure('TEntry',
padding=5,
relief='flat',
fieldbackground=self.colors['surface'],
selectbackground=self.colors['primary'],
selectforeground=self.colors['text']
)
style.map('TEntry',
relief=[('focus', 'flat')],
bordercolor=[('focus', self.colors['primary'])]
)
# Frame and Label
style.configure('TFrame', background=self.colors['background'])
style.configure('TLabel', background=self.colors['background'])
# Treeview
style.configure('Treeview',
background=self.colors['surface'],
foreground=self.colors['text'],
fieldbackground=self.colors['surface'],
rowheight=25,
borderwidth=0
)
style.configure('Treeview.Heading',
background=self.colors['surface'],
foreground=self.colors['text'],
relief='flat',
borderwidth=0,
padding=5
)
style.map('Treeview',
background=[('selected', self.colors['primary'])],
foreground=[('selected', '#FFFFFF')]
)
style.map('Treeview.Heading',
relief=[('active', 'flat')],
background=[('active', self.colors['hover'])]
)
# Scrollbar
for orient in ['Vertical', 'Horizontal']:
style.configure(f'{orient}.TScrollbar',
background=self.colors['surface'],
troughcolor=self.colors['background'],
relief='flat',
borderwidth=0,
arrowsize=0
)
style.map(f'{orient}.TScrollbar',
relief=[('pressed', 'flat')],
background=[
('pressed', self.colors['primary']),
('active', self.colors['hover'])
]
)
# Card style for calculator
style.configure('Card.TFrame',
background=self.colors['surface'],
relief='flat',
borderwidth=1,
padding=10
)
# Configure root window
if isinstance(root, (tk.Tk, tk.Toplevel)):
root.configure(bg=self.colors['background'])
# Apply theme to all widgets
self._apply_to_widget(root)
return style
def _apply_to_widget(self, widget):
"""
Recursively apply the theme to a widget and its children.
Args:
widget (Union[ttk.Widget, tk.Widget]): The widget to apply the theme to.
"""
if isinstance(widget, ttk.Widget):
# TTK widgets use style system
widget_class = widget.winfo_class()
if widget_class == 'TButton' and 'Toggle' in str(widget.cget('style')):
widget.configure(style='Toggle.TButton')
elif widget_class in ['TFrame', 'TLabelframe']:
# Skip style application for frames
pass
elif widget_class.startswith('T'):
# For other ttk widgets, use their existing class name
widget.configure(style=widget_class)
elif isinstance(widget, tk.Widget):
# Handle non-TTK widgets
if isinstance(widget, tk.Canvas):
widget.configure(
bg=self.colors['surface'],
highlightthickness=0,
bd=0
)
elif isinstance(widget, tk.Text):
widget.configure(
bg=self.colors['surface'],
fg=self.colors['text'],
insertbackground=self.colors['text'],
selectbackground=self.colors['primary'],
selectforeground=self.colors['text'],
font=self.fonts['body']
)
elif isinstance(widget, (tk.Tk, tk.Toplevel)):
widget.configure(bg=self.colors['background'])
# Apply to children
for child in widget.winfo_children():
self._apply_to_widget(child)
def toggle_theme(self):
"""Toggle between dark and light theme modes."""
self.is_dark = not self.is_dark
self.update_colors()
# Save theme preference
self.settings["theme"] = "dark" if self.is_dark else "light"
save_settings(self.settings)
class Supplement:
"""
Represents a supplement.
This class encapsulates the data and behavior of a supplement, including its name,
counts, cost, tags, link, and daily dose.
"""
def __init__(self, name: str, current_count: int, initial_count: int,
cost: float, tags: List[str], link: str, daily_dose: int, auto_decrement: bool = True):
"""
Initialize a new Supplement.
Args:
name (str): The name of the supplement.
current_count (int): The current count of the supplement.
initial_count (int): The initial count of the supplement.
cost (float): The cost of the supplement.
tags (List[str]): A list of tags associated with the supplement.
link (str): A link to the supplement (e.g., purchase URL).
daily_dose (int): The recommended daily dose of the supplement.
auto_decrement (bool): Whether to automatically decrement the count daily (default: True).
"""
self.name = name
self.current_count = current_count
self.initial_count = initial_count
self.cost = cost
self.tags = tags
self.link = link
self.daily_dose = daily_dose
self.auto_decrement = auto_decrement
self.last_updated = datetime.now().strftime("%Y-%m-%d")
def to_dict(self) -> Dict:
"""
Convert the Supplement to a dictionary.
Returns:
Dict: A dictionary representation of the Supplement.
"""
return {
'name': self.name,
'current_count': self.current_count,
'initial_count': self.initial_count,
'cost': self.cost,
'tags': self.tags,
'link': self.link,
'daily_dose': self.daily_dose,
'auto_decrement': self.auto_decrement,
'last_updated': self.last_updated
}
@classmethod
def from_dict(cls, data: Dict):
"""
Create a Supplement from a dictionary.
Args:
data (Dict): A dictionary containing the Supplement data.
Returns:
Supplement: A Supplement instance created from the dictionary.
"""
supplement = cls(
data['name'],
data['current_count'],
data['initial_count'],
data['cost'],
data['tags'],
data['link'],
data['daily_dose'],
data.get('auto_decrement', True) # Default to True for backward compatibility
)
supplement.last_updated = data['last_updated']
return supplement
def days_remaining(self) -> float:
"""
Calculate the number of days remaining based on the current count and daily dose.
Returns:
float: The number of days remaining. Returns infinity if daily dose is zero.
"""
if self.daily_dose == 0:
return float('inf')
return self.current_count / self.daily_dose
def update_count(self):
"""Update the current count based on the time passed since the last update."""
if not self.auto_decrement:
return
last_updated = datetime.strptime(self.last_updated, "%Y-%m-%d")
days_passed = (datetime.now() - last_updated).days
doses_taken = days_passed * self.daily_dose
self.current_count = max(0, self.current_count - doses_taken)
self.last_updated = datetime.now().strftime("%Y-%m-%d")
class SupplementTracker:
"""
The main Supplement Tracker application.
This class represents the Supplement Tracker application window and its functionality.
It allows users to manage their supplement inventory, calculate costs, and more.
"""
def __init__(self, initial_file=None):
"""
Initialize the SupplementTracker.
Args:
initial_file (str): The path to the initial supplement data file (default: None).
"""
try:
self.root = tk.Tk()
self.root.title("Supplement Tracker")
self.root.geometry("1000x700")
# Load settings and apply theme
self.settings = load_settings()
self.theme = ModernTheme(is_dark=None) # Use saved theme preference
self.style = self.theme.apply(self.root)
# Initialize backup manager
self.backup_manager = BackupManager(self.settings)
# Set up file association handling
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
self.root.createcommand('::tk::mac::OpenDocument', self.open_file_from_system)
self.supplements: List[Supplement] = []
self.setup_gui()
# Add global keyboard shortcuts with feedback
self.root.bind("<Control-s>", lambda event: self.save_with_feedback())
# Load initial file or last used file
if initial_file and os.path.exists(initial_file):
self.load_supplements(initial_file)
elif self.settings.get("last_file") and os.path.exists(self.settings["last_file"]):
self.load_supplements(self.settings["last_file"])
else:
self.load_supplements()
except Exception as e:
handle_error(e, "Failed to initialize application")
sys.exit(1)
def update_title(self, text):
"""
Update the window title.
Args:
text (str): The new window title.
"""
self.root.title(text)
def on_closing(self):
"""Handle window closing."""
if self.supplements:
if messagebox.askyesno("Save Changes", "Would you like to save changes before closing?"):
# Save with user initiation flag
self.save_supplements(self.settings.get("last_file", "supplements.sup"), is_user_initiated=True)
else:
# Create a backup even if user chooses not to save
if self.settings.get("last_file"):
self.backup_manager.create_backup(self.settings["last_file"], is_auto_save=False)
self.root.destroy()
def open_file_from_system(self, filename):
"""
Handle system file open requests.
Args:
filename (str): The path to the file to open.
"""
try:
self.load_supplements(filename)
except Exception as e:
messagebox.showerror("Error", f"Failed to open file: {str(e)}")
def setup_gui(self):
"""Set up the main GUI elements of the application."""
# Create main frames with padding
main_frame = ttk.Frame(self.root, padding="10", style='TFrame')
main_frame.pack(fill='both', expand=True)
self.control_frame = ttk.Frame(main_frame, style='TFrame')
self.control_frame.pack(fill='x', pady=(0, 10))
# Button frame with modern spacing
button_frame = ttk.Frame(self.control_frame, style='TFrame')
button_frame.pack(side='left')
# Add controls with consistent spacing
buttons = [
("Add Supplement", self.show_add_dialog),
("Remove Selected", self.remove_selected),
("Cost Calculator", self.show_calculator),
("Save As...", self.save_as),
("Load File", self.load_file),
("Backups", self.show_backups),
("Settings", self.show_settings)
]
for text, command in buttons:
btn = ttk.Button(button_frame, text=text, command=command)
btn.pack(side='left', padx=5)
# Theme toggle button
def toggle_theme():
self.theme.toggle_theme()
self.style = self.theme.apply(self.root)
# Update theme button text and all windows
theme_btn.configure(text="🌙 Dark" if not self.theme.is_dark else "☀️ Light")
for window in self.root.winfo_children():
if isinstance(window, tk.Toplevel):
self.theme._apply_to_widget(window)
theme_btn = ttk.Button(
button_frame,
text="🌙 Dark" if not self.theme.is_dark else "☀️ Light",
command=toggle_theme,
style='Toggle.TButton'
)
theme_btn.pack(side='left', padx=5)
# Search frame with modern look
search_frame = ttk.Frame(self.control_frame)
search_frame.pack(side='right', padx=5)
ttk.Label(search_frame, text="Search:").pack(side='left', padx=(0, 5))
self.search_var = tk.StringVar()
self.search_var.trace('w', lambda *args: self.update_list())
search_entry = ttk.Entry(search_frame, textvariable=self.search_var, width=30)
search_entry.pack(side='left')
# Create treeview with modern styling
self.list_frame = ttk.Frame(main_frame)
self.list_frame.pack(fill='both', expand=True)
# Add scrollbars with modern styling
tree_scroll_y = ttk.Scrollbar(self.list_frame, orient="vertical", style='Vertical.TScrollbar')
tree_scroll_y.pack(side='right', fill='y')
tree_scroll_x = ttk.Scrollbar(self.list_frame, orient="horizontal", style='Horizontal.TScrollbar')
tree_scroll_x.pack(side='bottom', fill='x')
# Create and configure treeview
self.tree = ttk.Treeview(self.list_frame,
columns=('Name', 'Count', 'Initial', 'Cost', 'Tags', 'Daily', 'Days Left'),
yscrollcommand=tree_scroll_y.set,
xscrollcommand=tree_scroll_x.set,
style='Treeview'
)
# Hide the first empty column
self.tree['show'] = 'headings'
# Configure scrollbars
tree_scroll_y.config(command=self.tree.yview)
tree_scroll_x.config(command=self.tree.xview)
# Configure column headings with explicit styles
column_widths = {
'Name': (150, 100),
'Count': (70, 50),
'Initial': (70, 50),
'Cost': (80, 60),
'Tags': (150, 100),
'Daily': (80, 60),
'Days Left': (80, 60)
}
for col in column_widths:
width, minwidth = column_widths[col]
self.tree.heading(col, text=col, anchor='w')
self.tree.column(col, width=width, minwidth=minwidth, anchor='w')
# Configure tag for items with auto-decrement disabled
self.tree.tag_configure('no_auto_decrement', foreground='#FF6B6B')
self.tree.pack(fill='both', expand=True)
# Bind right-click event to show context menu
self.tree.bind("<Button-3>", self.show_context_menu)
# Add legend for the asterisk indicator
legend_frame = ttk.Frame(main_frame)
legend_frame.pack(fill='x', pady=(5, 0))
legend_label = ttk.Label(
legend_frame,
text="* Items with asterisk have auto-decrement disabled",
font=self.theme.fonts['small'],
foreground=self.theme.colors['text_secondary']
)
legend_label.pack(side='right', padx=5)
def show_add_dialog(self):
"""Show the dialog for adding a new supplement."""
dialog = tk.Toplevel(self.root)
dialog.title("Add Supplement")
dialog.geometry("500x400")
# Apply theme to dialog
self.theme._apply_to_widget(dialog)
# Make dialog modal
dialog.transient(self.root)
dialog.grab_set()
# Create main frame with padding
main_frame = ttk.Frame(dialog, padding="20")
main_frame.pack(fill='both', expand=True)
# Create entry fields
entries = {}
fields = [
('name', "Name:"),
('count', "Current Count:"),
('initial', "Initial Count:"),
('cost', "Cost:"),
('tags', "Tags (comma-separated):"),
('link', "Link:"),
('daily', "Daily Dose:")
]
# Calculate maximum label width
max_label_width = max(len(label) for _, label in fields)
for key, label in fields:
frame = ttk.Frame(main_frame)
frame.pack(fill='x', pady=5)
label_widget = ttk.Label(frame, text=label, width=max_label_width + 2)
label_widget.pack(side='left')
entry = ttk.Entry(frame)
entry.pack(side='right', expand=True, fill='x', padx=(10, 0))
entries[key] = entry
# Add auto-decrement checkbox
auto_decrement_frame = ttk.Frame(main_frame)
auto_decrement_frame.pack(fill='x', pady=5)
auto_decrement_var = tk.BooleanVar(value=True)
auto_decrement_check = ttk.Checkbutton(
auto_decrement_frame,
text="Auto-decrement daily",
variable=auto_decrement_var
)
auto_decrement_check.pack(side='left')
# Button frame
button_frame = ttk.Frame(main_frame)
button_frame.pack(pady=(20, 0))
ttk.Button(button_frame, text="Save", command=lambda: save()).pack(side='left', padx=5)
ttk.Button(button_frame, text="Cancel", command=dialog.destroy).pack(side='left', padx=5)
def save():
try:
supplement = Supplement(
entries['name'].get(),
int(entries['count'].get()),
int(entries['initial'].get()),
float(entries['cost'].get()),
[tag.strip() for tag in entries['tags'].get().split(',')],
entries['link'].get(),
int(entries['daily'].get()),
auto_decrement_var.get()
)
self.supplements.append(supplement)
self.save_supplements()
self.update_list()
dialog.destroy()
except ValueError as e:
messagebox.showerror("Error", "Please check your input values")
def remove_selected(self):
"""Remove the selected supplement(s) from the list."""
selected = self.tree.selection()
if not selected:
return
if messagebox.askyesno("Confirm", "Are you sure you want to remove the selected supplement?"):
for item_id in selected:
index = int(item_id)
if 0 <= index < len(self.supplements):
del self.supplements[index]
self.save_supplements()
self.update_list()
def show_calculator(self):
"""Show the cost calculator dialog."""
calc = tk.Toplevel(self.root)
calc.title("Cost Calculator")
calc.geometry("800x600")
calc.configure(bg=self.theme.colors['background'])
# Apply theme to calculator window
self.theme._apply_to_widget(calc)
# Make calculator modal
calc.transient(self.root)
calc.grab_set()
main_frame = ttk.Frame(calc, padding="20", style='TFrame')
main_frame.pack(fill='both', expand=True)
# Title
title_label = ttk.Label(main_frame,
text="Compare Supplement Costs",
font=self.theme.fonts['heading'],
style='TLabel'
)
title_label.pack(pady=(0, 20))
# Create container frame for canvas
canvas_container = ttk.Frame(main_frame, style='TFrame')
canvas_container.pack(fill='both', expand=True)
canvas_container.grid_rowconfigure(0, weight=1)
canvas_container.grid_columnconfigure(0, weight=1)
# Scrollable frame for options
canvas = tk.Canvas(
canvas_container,
bg=self.theme.colors['background'],
highlightthickness=0,
bd=0
)
scrollbar = ttk.Scrollbar(canvas_container, orient="vertical", command=canvas.yview, style='Vertical.TScrollbar')
options_frame = ttk.Frame(canvas, style='TFrame')
# Configure canvas
canvas.configure(yscrollcommand=scrollbar.set)
# Grid layout for better control
canvas.grid(row=0, column=0, sticky='nsew')
scrollbar.grid(row=0, column=1, sticky='ns')
# Create window in canvas
canvas_frame = canvas.create_window((0, 0), window=options_frame, anchor='nw', width=canvas.winfo_width())
options = []
option_frames = []
def on_configure(event):
canvas.configure(scrollregion=canvas.bbox("all"))
canvas.itemconfig(canvas_frame, width=event.width)