-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2461 lines (1885 loc) · 97.2 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
#!/usr/bin/env python
####################################################################################################################################################################
### ZWEGAT ALPHA ###################################################################################################################################################
####################################################################################################################################################################
'''
Author: - Johannes Wiesner
Notes: - Debts are not rounded until saving in txt-file or presenting in text-widget
- Please help me fixing all FIXMES!
- all rasperry pi specific lines are commented with "rp3:..."
'''
####################################################################################################################################################################
### Import Modules #################################################################################################################################################
####################################################################################################################################################################
# Modules for Zwegat Alpha
import os
import datetime
import subprocess
import pickle
from collections import Counter
# Modules for tkinter-GUI
import tkinter as tk
from tkinter import ttk
from PIL import Image
from PIL import ImageTk
from tkinter import messagebox
import sys
# pygame for optional playing of audio files
import pygame
# vlc radio for radio page
# import vlc
# weather modules
import json
import codecs
from urllib.request import urlopen
# rp3
# if sys.platform == "linux":
# import cups
# else:
# pass
##############################################################################################################################################################
### Set System Variables #####################################################################################################################################
##############################################################################################################################################################
# Date
tday = datetime.date.today().strftime('%Y/%m/%d')
##############################################################################################################################################################
### MODEL ####################################################################################################################################################
##############################################################################################################################################################
# FIXME: The whole special expense part (variables, methods, classmethods) is so similar to the expense stuff (except that all variables and
# function names have a spcl_ in their name) that I wonder if there's a more elegant way to do this? Status quo is basically a modified copy of all
# instance variables and methods & classmethods.
# Define Class Roomie
class Roomie:
num_roomies = 5 # number of roomies
total_exp = 0.00 # sum of all expenses
total_spcl_exp = 0.00 # sum of all special expenses
mean_exp = 0.00 # mean expenses
mean_spcl_exp = 0.00 # mean special expenses
num_exp = 0 # total count of all expenses for one debts plan
num_spcl_exp = 0 # total count of all expenses for one debts plan
# FIXME: How to declare exp, res correctly in pythonic way?
def __init__(self, fname,exp=0.00,res=0.00,exlist=None,info=None,date=None,pres=None,preslist=None,evlist=None,
spcl_exp=0.00,spcl_res=0.00,spcl_exlist=None,spcl_info=None,spcl_date=None,partlist=None,spcl_evlist=None):
## -- EXPENSE -----------------------------------------------------------------------------------------
self.fname = fname # roomie name
self.exp = exp # roomie expenses
self.res = res # difference roomie expenses to total mean
self.exlist = [] # list of single roomie expenses
self.info = [] # list of info for each expense
self.date = [] # list of dates each expense was done
# Additional information for conservative debt calculation
self.pres = True # boolean value: current presence status of roomie (present/absent)
self.preslist = [] # list of presence status for expense events
self.evlist = [] # list of expense events (if spender: amount / if not spender: None)
## -- SPECIAL EXPENSE ----------------------------------------------------------------------------------
self.spcl_exp = spcl_exp # roomie special expenses
self.spcl_res = spcl_res # difference roomie total special expenses to total special expenses mean
self.spcl_exlist = [] # list of special roomie expenses
self.spcl_info = [] # list of info for each special expense
self.spcl_date = [] # list of dates each special expense was done
# Additional information for special expense debt calculation
self.partlist = [] # list of participation status for expense events
self.spcl_evlist = [] # list of special expense events (if spender: amount / if not spender: None)
## -- EXPENSE METHODS ----------------------------------------------------------------------------------
def raiseExp(self,expense):
self.exp = (self.exp + expense)
def updateRes(self,mean_exp):
self.res = self.exp - mean_exp
def addEx(self,exp):
self.exlist.append(exp)
def addInfo(self,exp_info):
self.info.append(exp_info)
def addDate(self,tday):
self.date.append(tday)
def changePres(self,switch):
self.pres = switch
def addPres(self):
self.preslist.append(self.pres)
def addEv(self,expense):
self.evlist.append(expense)
## -- SPECIAL EXPENSE METHODS --------------------------------------------------------------------------
def raiseSpclExp(self,expense):
self.spcl_exp = (self.spcl_exp + expense)
def updateSpclRes(self,mean_spcl_exp):
self.spcl_res = self.spcl_exp - mean_spcl_exp
def addSpclEx(self,special):
self.spcl_exlist.append(special)
def addSpclInfo(self,specialinfo):
self.spcl_info.append(specialinfo)
def addSpclDate(self,tday):
self.spcl_date.append(tday)
def addPart(self,switch):
self.partlist.append(switch)
def addSpclEv(self,special):
self.spcl_evlist.append(special)
## -- RESET INSTANCE -----------------------------------------------------------------------------------------------------------
# FIXME: - Is there a better way to "reset" the instance without hardcoding?
# - This version is basically a "pseudo" init-call
def resetObject(self, exp=0.00,res=0.00,exlist=None,info=None,date=None,pres=None,preslist=None,evlist=None,
spcl_exp=0.00,spcl_res=0.00,spcl_exlist=None,spcl_info=None,spcl_date=None,partlist=None,spcl_evlist=None):
self.exp = exp
self.res = res
self.exlist = []
self.info = []
self.date = []
self.pres = True
self.preslist = []
self.evlist = []
self.spcl_exp = spcl_exp
self.spcl_res = spcl_res
self.spcl_exlist = []
self.spcl_info = []
self.spcl_date = []
self.partlist = []
self.spcl_evlist = []
## -- CLASSMETHODS - EXPENSES ---------------------------------------------------------------------------------------
@classmethod
def raiseTotalExp(cls,single):
cls.total_exp = cls.total_exp + single
@classmethod
def raiseMeanExp(cls):
cls.mean_exp = cls.total_exp / cls.num_roomies
@classmethod
def updateExpNum(cls):
cls.num_exp += 1
## -- CLASSMETHODS - SPECIAL EXPENSES -------------------------------------------------------------------------------
@classmethod
def raiseSpclTotalExp(cls,special):
cls.total_spcl_exp = cls.total_spcl_exp + special
@classmethod
def raiseSpclMeanExp(cls):
cls.mean_spcl_exp = cls.total_spcl_exp / cls.num_roomies
@classmethod
def updateSpclExpNum(cls):
cls.num_spcl_exp += 1
## -- RESET CLASS VARIABLES ---------------------------------------------------------------------------------------
@classmethod
def resetClass(cls):
cls.num_roomies = 5
cls.total_exp = 0.00
cls.total_spcl_exp = 0.00
cls.mean_exp = 0.00
cls.mean_spcl_exp = 0.00
cls.num_exp = 0
cls.num_spcl_exp = 0
# Define Class Roomie instances
roomie_0 = Roomie("Roomie 1")
roomie_1 = Roomie("Roomie 2")
roomie_2 = Roomie("Roomie 3")
roomie_3 = Roomie("Roomie 4")
roomie_4 = Roomie("Roomie 5")
# Create roomie list for later use in functions
# FIXME: It would probably have been better to use dictionary type here?
roomie_list = [roomie_0,roomie_1,roomie_2,roomie_3,roomie_4]
# Function: liberalDebtsDict
# Take: all roomie.res
# Return: dictionary with keys = roomie number, values = debts / demands
# Note: this returns liberal debts dictionary (presence status is not considered)
def liberalDebtsDict():
debts_dict = {}
for (i,person) in zip(range(0,len(roomie_list)), roomie_list):
debts_dict[i] = person.res
return debts_dict
# Function: conservativeDebtsDict
# Take: evlist of all roomies, preslist of all roomies
# Return: Dictionary with keys = roomie number, values = debts/demands
# Note: this returns conservative debts dictionary: debts are ADJUSTED FOR PRESENCE
def conservativeDebtsDict():
hit = None # saves the current number of roomie who made a purchase
ev_exp = None # saves the current expense for this roomie
ev_list_pres = [] # saves current indices for all roomies who were present at this event
ev_debts = None # saves current debts for all present roomies
# Output:
presence_adjusted_dict = {}
for i in range(0,len(roomie_list)):
presence_adjusted_dict[i] = 0
# for idxth-event: who made a purchase? Save number in hit variable
# for idxth-event: how much did this roomie spent? Save value in ev_exp variable
# for idxth-event: who was present? Save roomie number in ev_list_pres
for idx in range(0,Roomie.num_exp):
for roomie in roomie_list:
if roomie.evlist[idx] != None:
hit = roomie_list.index(roomie)
ev_exp = roomie_list[hit].evlist[idx]
if roomie.preslist[idx] == True:
ev_list_pres.append(roomie_list.index(roomie))
else:
pass
# for idxth event: calculate debts depending on present roomies
ev_debts = ev_exp / len(ev_list_pres)
# only for present roomies: add ev_debts
for spender in ev_list_pres :
presence_adjusted_dict[spender] += ev_debts
# reset presence list
ev_list_pres = []
# after going trough all events: substract individual debts from individual expenses
for roomie in presence_adjusted_dict:
presence_adjusted_dict[roomie] = roomie_list[roomie].exp - presence_adjusted_dict[roomie]
return presence_adjusted_dict
# Function: SpecialExpenseDict
# Take: spcl_evlist of all roomies, partlist of all roomies
# Return: special expense dictionary with keys = roomie number, values = debts/demands
# FIXME: This is basically a copy of conservative debts dict but with different variables
# -> Merge two functions together, by writing generic function that takes instance attributs as arguments
def specialExpenseDebtsDict():
hit = None # saves the current number of roomie who made a purchase
ev_exp = None # saves the current special expense for this roomie
ev_list_part = [] # saves current indices for all roomies participating in this event
ev_debts = None # saves current special debts for all present roomies
# Output:
special_expense_dict = {}
for i in range(0,len(roomie_list)):
special_expense_dict[i] = 0
# for idxth-event: who made a purchase? Save number in hit variable
# for idxth-event: how much did this roomie spent? Save value in ev_exp variable
# for idxth-event: who was present? Save roomie number in ev_list_part
for idx in range(0,Roomie.num_spcl_exp):
for roomie in roomie_list:
if roomie.spcl_evlist[idx] != None:
hit = roomie_list.index(roomie)
ev_exp = roomie_list[hit].spcl_evlist[idx]
if roomie.partlist[idx] == True:
ev_list_part.append(roomie_list.index(roomie))
else:
pass
# for idxth event: calculate debts depending on present roomies
ev_debts = ev_exp / len(ev_list_part)
# only for present roomies: add ev_debts
for spender in ev_list_part :
special_expense_dict[spender] += ev_debts
# reset presence list
ev_list_part = []
# after going trough all events: substract individual debts from individual expenses
for roomie in special_expense_dict:
special_expense_dict[roomie] = roomie_list[roomie].spcl_exp - special_expense_dict[roomie]
return special_expense_dict
# Take: Dictionary with keys = roomie number, values = debts / demands
# Do: Sort dictionary by values but keep corresponding keys
# Note: See also 'OrderedDict Subclass' from 'collections' module
# Return: Value-sorted dictionary
def valueSortedDict(my_dict):
keys = list(my_dict.keys())
values = list(my_dict.values())
# Note: values get sorted in ascending order from negative to positive
values_sorted = sorted(my_dict.values())
keys_sorted = []
for i in range(0,len(my_dict)):
values_sorted_val = values_sorted[i]
values_idx = values.index(values_sorted_val)
# First: cut out value from original list to prevent from finding this value again using index method
# Second: insert string type to prevent list from shrinking
values.pop(values_idx)
values.insert(values_idx,'checked')
key_val = keys[values_idx]
keys_sorted.append(key_val)
my_sorted_dict = dict(zip(keys_sorted, values_sorted))
return my_sorted_dict
# Normalize Function
# Take: dictionary with keys = roomie number, values = debts (negative values) / demands (positive values)
# Return: list with 3-element-tuples (Debtor,Creditor,Amount)
def normalizeDebts(my_dict):
keys = list(my_dict.keys())
values = list(my_dict.values())
stack_list = values
debts_list = list()
while any(element != 0 for element in stack_list):
cur_max_idx = stack_list.index(max(stack_list))
cur_min_idx = stack_list.index(min(stack_list))
cur_max_val = stack_list[cur_max_idx]
cur_min_val = stack_list[cur_min_idx]
if abs(cur_min_val) < abs(cur_max_val) and cur_min_val < 0 and cur_max_val > 0:
stack_list[cur_min_idx] = cur_min_val + abs(cur_min_val)
stack_list[cur_max_idx] = cur_max_val - abs(cur_min_val)
debts_list.append((keys[cur_min_idx],keys[cur_max_idx],abs(cur_min_val)))
elif abs(cur_min_val) > abs(cur_max_val) and cur_min_val < 0 and cur_max_val > 0:
stack_list[cur_min_idx] = cur_min_val + abs(cur_max_val)
stack_list[cur_max_idx] = cur_max_val - abs(cur_max_val)
debts_list.append((keys[cur_min_idx],keys[cur_max_idx],abs(cur_max_val)))
elif abs(cur_min_val) == abs(cur_max_val):
stack_list[cur_min_idx] = 0
stack_list[cur_max_idx] = 0
debts_list.append((keys[cur_min_idx],keys[cur_max_idx],abs(cur_min_val)))
else:
break
return debts_list
def mergeDebts():
debts_dict = Counter(conservativeDebtsDict())
spcl_dict = Counter(specialExpenseDebtsDict())
debts_dict.update(spcl_dict)
return debts_dict
# Function: saveDebtsTxt
# Take: Conservative / liberal debts list (3-element-tuples)
# Do: Save current debts plan as txt file
# Return: Path of txt-file for later optional printing
# FIXME: Any way to make variable hyphen dynamic? (hyphen line as long as longest line in text widget)
def saveDebtsTxt(debts_list):
HYPHEN = "-" * 70
doc_date = datetime.date.today().strftime('%Y_%B')
zipped = []
conservative_debtslist = normalizeDebts(valueSortedDict(conservativeDebtsDict()))
special_debtslist = normalizeDebts(valueSortedDict(specialExpenseDebtsDict()))
global_debtslist = normalizeDebts(valueSortedDict(mergeDebts()))
# Create functions for easy writing standard characters such as newline, etc.
def write(text):
file.write(text)
def newLine():
file.write("\n")
def doubleNewLine():
file.write("\n\n")
def hyphenLine():
file.write("{}\n\n".format(HYPHEN))
# Open file
file = open("RausAusDenSchulden_{}.txt".format(doc_date),"w")
write("Abrechnungsdatum:\t{}".format(datetime.date.today().strftime("%d.%m.%Y")))
doubleNewLine()
hyphenLine()
# Write expenses for each roomie including exp_info and date
write("Normale Ausgaben:")
doubleNewLine()
for roomie in roomie_list:
write("{}:".format(roomie.fname))
doubleNewLine()
zipped = list(zip(roomie.date,roomie.exlist,roomie.info))
for (date,exp,info) in zipped:
if info != None:
write("{}\t\t{}€\t{}\n".format(date,exp,info))
elif info == None:
write("{}\t\t{}€\t{}\n".format(date,exp,""))
newLine()
hyphenLine()
# Write global info
write("Totale Ausgaben:\t\t{}€\nMittelwert:\t\t\t{}€\nGesamtzahl getätigter Ausgaben:\t{}".format(round(Roomie.total_exp,2),round(Roomie.mean_exp,2),Roomie.num_exp))
doubleNewLine()
# Write debts plan
write("Konservativer Schuldenplan:")
doubleNewLine()
for (creditor,debtor,amount) in conservative_debtslist:
write('{} schuldet {} {}€\t\n'.format(roomie_list[creditor].fname,roomie_list[debtor].fname,round(amount,2)))
newLine()
hyphenLine()
# Write special expenses for each roomie including info and date
write("Sonderausgaben:")
doubleNewLine()
for roomie in roomie_list:
write("{}:".format(roomie.fname))
doubleNewLine()
zipped = list(zip(roomie.spcl_date,roomie.spcl_exlist,roomie.spcl_info))
for (date,exp,info) in zipped:
if info != None:
write("{}\t\t{}€\t{}\n".format(date,exp,info))
elif info == None:
write("{}\t\t{}€\t{}\n".format(date,exp,""))
newLine()
hyphenLine()
# Write global info
write("Totale Sonderausgaben:\t\t\t{}€\nMittelwert:\t\t\t\t{}€\nGesamtzahl getätigter Sonderausgaben:\t{}".format(round(Roomie.total_spcl_exp,2),
round(Roomie.mean_spcl_exp,2),Roomie.num_spcl_exp))
doubleNewLine()
# Write debts plan
write("Sonderausgaben Schuldenplan:")
doubleNewLine()
for (debtor,creditor,amount) in special_debtslist:
write('{} schuldet {} {}€\t\n'.format(roomie_list[debtor].fname,roomie_list[creditor].fname,round(amount,2)))
newLine()
hyphenLine()
write("Gesamtschuldenplan:")
for (debtor,creditor,amount) in global_debtslist:
write('{} schuldet {} {}€\t\n'.format(roomie_list[debtor].fname,roomie_list[creditor].fname,round(amount,2)))
# save filepath
file_path = str(os.path.realpath(file.name))
file.close()
return file_path
# Take: Path of current debtsplan-text
# Do: Print this txt-file
# Note: Implemented if-statement based on current os
def printDebtsPlan():
# windows
if sys.platform == "win32":
os.startfile(saveDebtsTxt(normalizeDebts(valueSortedDict(conservativeDebtsDict()))),"print")
# rp3
elif sys.platform == "linux":
conn = cups.Connection()
printers = conn.getPrinters()
# Note: Only to check which printers are available
for printer in printers:
print(printer,printers[printer]["device-uri"])
file = saveDebtsTxt(normalizeDebts(valueSortedDict(conservativeDebtsDict())))
printer_name = list(printers.keys())[0]
conn.printFile(printer_name,file,"",{})
else:
pass
##############################################################################################################################################################
### AUDIO ###################################################################################################################################################
##############################################################################################################################################################
sound_switch = True # Enable / Disable Sounds
pygame.mixer.pre_init(48000, 16, 2, 4096) #frequency, size, channels, buffersize
pygame.init() #turn all of pygame on.
sound_dict = {}
# load sounds
sound_dict[0] = pygame.mixer.Sound("audio/cash-register-purchase-87313.ogg")
sound_dict[1] = pygame.mixer.Sound("audio/cash-register-purchase-87313.ogg")
sound_dict[2] = pygame.mixer.Sound("audio/cash-register-purchase-87313.ogg")
sound_dict[3] = pygame.mixer.Sound("audio/cash-register-purchase-87313.ogg")
sound_dict[4] = pygame.mixer.Sound("audio/cash-register-purchase-87313.ogg")
def playSound(rsound):
if sound_switch == True:
pygame.mixer.Sound.play(rsound)
##############################################################################################################################################################
### INPUT ####################################################################################################################################################
##############################################################################################################################################################
# FIXME: Input.presence is not necessary -> Replace Switch Button on Page 20 with Checkbutton-Widget
# Associate boolean var with Checkbutton
# When user presses safe -> change instance attribute based on roomie_slc and boolean var value
class Input:
# which roomie is selected?
roomie_slc = None
# user switch input: roomie is absent / roomie is present
presence = None
# function: reset Input variables
@classmethod
def resetInput(cls):
cls.roomie_slc = None
cls.presence = None
####################################################################################################################################################################
### CONTROLLER #####################################################################################################################################################
####################################################################################################################################################################
# font constants
BUTTON_FONT=("Arial 11 bold italic")
TEXT_WIDGET_FONT = ("Arial", 11)
class Zwegat(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# rp3
# set main window size to rasperry pi 7" touchscreen size
tk.Tk.geometry(self,"800x480")
# application title
tk.Tk.title(self,"Zwegat Alpha")
# application icon
# FIXME: iconbitmap-method doesn't work on linux.
if sys.platform == "win32":
tk.Tk.iconbitmap(self,"images/zwegat.ico")
elif sys.platform == "linux":
# do something that displays icon on linux
pass
# application cursor
tk.Tk.configure(self,cursor="heart")
# Create standard frame - all frames are build upon this frame
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (Page00,Page01,Page10,Page20,Page21,Page22,Page30,Page40,Page50,Page60):
frame = F(container,self)
self.frames[F] = frame
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
frame.grid(row=0, column=0, sticky="NSEW")
# avoid this first class, automatically show Page10
self.showFrame(Page00)
# Wrapper Function (get arbitrary number of functions (with arbitrary number of arguments) and call them)
def wrapper(self,*funcs):
def combined_func(*args,**kwargs):
for f in funcs:
f(self,*args, **kwargs)
return combined_func
# Function: show frame with page name as argument
def showFrame(self, cont):
frame = self.frames[cont]
frame.tkraise()
# Function: Select Roomie
def slcRoomie(self,r):
Input.roomie_slc=r
# Function: After selecting roomie on Page10, check current presence status of this particular
# roomie and accordingly change switch button layout (this function should be called before showFrame-Function)
def checkStatus(self):
status = roomie_list[Input.roomie_slc].pres
button = self.frames[Page20].switch_0
red = self.frames[Page20].im_0_switch
green = self.frames[Page20].im_1_switch
if status == True:
button.config(relief="sunken")
button.config(image=green)
elif status == False:
button.config(relief="raised")
button.config(image=red)
# DAU-Function: Disallow anything but numbers, 1 dot and empty field
# FIXME: Double dots should be disallowed as well
# After whole line is deleted, function doesn't work anymore
def giveMeCash(self, d, i, P, s, S, v, V, W):
valid_characters = ["0","1","2","3","4","5","6","7","8","9","."]
# convert P into list with characters as separate string elements
listed_P = list(P)
if any(character == S for character in valid_characters) and len(P) < 7 and listed_P[0] != "." or P == "":
return True
else:
self.bell()
return False
# Function: transferExpInput
def transferExpInput(self,roomienum,expinput,infoinput):
amount=expinput.get()
info = infoinput.get()
roomie = roomie_list[roomienum]
# Only call instance methods if user entered an amount
if len(amount) > 0:
float_amount = float(amount)
# Call instance methods
roomie.raiseExp(float_amount)
roomie.addEx(float_amount)
roomie.addEv(float_amount)
roomie.addDate(tday)
# Call class methods
Roomie.raiseTotalExp(float_amount)
Roomie.raiseMeanExp()
Roomie.updateExpNum()
# Calculate new residuals
for person in roomie_list:
person.updateRes(Roomie.mean_exp)
# Update presence list
for person in roomie_list:
person.addPres()
# Add None-value to evlist for every roomie except the one that bought smth
custom_list = [x for i,x in enumerate(roomie_list) if i!=roomienum]
for person in custom_list:
person.addEv(None)
# add expense info if user gave input
if len(info) > 0:
roomie.addInfo(info)
elif len(info) == 0:
roomie.addInfo(None)
elif len(amount) == 0:
pass
# Function: transferExpInput
# FIXME: Same issue as in the init-method. This code is so similar to transferExpInput-function that I wonder if there's
# a generic function that could combine transferExpInput and transferSpclExpInput
def transferSpclExpInput(self,roomienum,expinput,infoinput):
amount=expinput.get()
info = infoinput.get()
roomie = roomie_list[roomienum]
# Only call instance methods if user entered an amount
if len(amount) > 0:
float_amount = float(amount)
# Call instance methods
roomie.raiseSpclExp(float_amount)
roomie.addSpclEx(float_amount)
roomie.addSpclEv(float_amount)
roomie.addSpclDate(tday)
# Call class methods
Roomie.raiseSpclTotalExp(float_amount)
Roomie.raiseSpclMeanExp()
Roomie.updateSpclExpNum()
# Calculate new residuals
for person in roomie_list:
person.updateSpclRes(Roomie.mean_exp)
# Add None-value to evlist for every roomie except the one that bought smth
custom_list = [x for i,x in enumerate(roomie_list) if i!=roomienum]
for person in custom_list:
person.addSpclEv(None)
# add expense info if user gave input
if len(info) > 0:
roomie.addSpclInfo(info)
elif len(info) == 0:
roomie.addSpclInfo(None)
elif len(amount) == 0:
pass
# FIXME: - Input.presence is redundant -> use Checkbutton with associated boolean var
# - Take value of boolean var as Input.presence
def transferStatusChange(self):
# call changePres-Function
roomie_list[Input.roomie_slc].changePres(Input.presence)
def registerParticipation(self):
for idx in range(0,len(roomie_list)):
roomie_list[idx].addPart(self.frames[Page22].part_dict[idx].get())
# Function:
# Do: Write current debts plan in text widget on Page30
# FIXME: Make hypen-variable dynamic based on longest line in text-widget
def writeTextWidget(self):
conservative_debtslist = normalizeDebts(valueSortedDict(conservativeDebtsDict()))
special_debtslist = normalizeDebts(valueSortedDict(specialExpenseDebtsDict()))
global_debtslist = normalizeDebts(valueSortedDict(mergeDebts()))
text_w = self.frames[Page30].text_0
HYPHEN = "-" * 75
doc_name = datetime.date.today().strftime('%Y_%B')
zipped = []
# Create functions for easy writing
def write(t):
text_w.insert("end",t)
def newLine():
text_w.insert("end","\n")
def doubleNewLine():
text_w.insert("end","\n\n")
def hyphenLine():
text_w.insert("end","{}\n\n".format(HYPHEN))
write("Abrechnungsdatum:\t{}".format(datetime.date.today().strftime("%d.%m.%Y")))
doubleNewLine()
hyphenLine()
# Write expenses for each roomie including exp_info and date
write("Normale Ausgaben:")
doubleNewLine()
for roomie in roomie_list:
write("{}:".format(roomie.fname))
doubleNewLine()
zipped = list(zip(roomie.date,roomie.exlist,roomie.info))
for (date,exp,info) in zipped:
if info != None:
write("{}\t\t{}€\t{}\n".format(date,exp,info))
elif info == None:
write("{}\t\t{}€\t{}\n".format(date,exp,""))
newLine()
hyphenLine()
# Write global info
write("Totale Ausgaben:\t\t\t\t{}€\nMittelwert:\t\t\t\t{}€\nGesamtzahl getätigter Ausgaben:\t\t\t\t{}".format(round(Roomie.total_exp,2),round(Roomie.mean_exp,2),Roomie.num_exp))
doubleNewLine()
# Write debts plan
write("Konservativer Schuldenplan:")
doubleNewLine()
for (creditor,debtor,amount) in conservative_debtslist:
write('{} schuldet {} {}€\t\n'.format(roomie_list[creditor].fname,roomie_list[debtor].fname,round(amount,2)))
newLine()
hyphenLine()
# Write special expenses for each roomie including info and date
write("Sonderausgaben:")
doubleNewLine()
for roomie in roomie_list:
write("{}:".format(roomie.fname))
doubleNewLine()
zipped = zip(roomie.spcl_date,roomie.spcl_exlist,roomie.spcl_info)
for (date,exp,info) in zipped:
print((date,exp,info))
if info != None:
write("{}\t\t{}€\t{}\n".format(date,exp,info))
elif info == None:
write("{}\t\t{}€\t{}\n".format(date,exp,""))
newLine()
hyphenLine()
# Write special info
write("Totale Sonderausgaben:\t\t\t\t\t{}€\nMittelwert:\t\t\t\t\t{}€\nGesamtzahl getätigter Sonderausgaben:\t\t\t\t\t{}".format(round(Roomie.total_spcl_exp,2),
round(Roomie.mean_spcl_exp,2),Roomie.num_spcl_exp))
doubleNewLine()
# Write special debts plan
write("Sonderausgaben Schuldenplan:")
doubleNewLine()
for (debtor,creditor,amount) in special_debtslist:
write('{} schuldet {} {}€\t\n'.format(roomie_list[debtor].fname,roomie_list[creditor].fname,round(amount,2)))
newLine()
hyphenLine()
write("Gesamtschuldenplan:")
doubleNewLine()
for (debtor,creditor,amount) in global_debtslist:
write('{} schuldet {} {}€\t\n'.format(roomie_list[debtor].fname,roomie_list[creditor].fname,round(amount,2)))
def enableTxtWidget(self):
self.frames[Page30].text_0.configure(state="normal")
def disableTxtWidget(self,txtwidget):
txtwidget.configure(state="disabled")
# Function: delete TextWidgetContent
def deleteTxtWidget(self,txtwidget):
txtwidget.configure(state="normal")
txtwidget.delete("1.0","end")
def deleteListbox(self,listbox):
listbox.delete("0","end")
def writeForecast(self,txtwidget):
txtwidget.configure(state="normal")
def write(text):
txtwidget.insert("end",text)
# grab forecast data from openweathermap api
# returns dictionary with forecast data for the next 5 days / 3 hr interval - accordingly 40 values in dictionary
def GrabForecast():
lat = ""
lon = ""
appId = ""
weatherUrl = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + lat + '&lon=' + lon + '&lang=de&units=metric&appid=' + appId
try:
jsonFile = urlopen(weatherUrl)
jsonFileContent = jsonFile.read().decode('utf-8')
jsonObject = json.loads(jsonFileContent)
forecast_dict = {}
for idx in range(0,40):
forecast_dict[idx] = jsonObject['list'][idx]
return forecast_dict
except:
print("error")
# create customized forecast dictionary only needed forecast information (interval can be changed by adjusting step size in for loop)
def returnMyForecast(forecast,interval=1):
def formatTimestamp(timestamp):
return datetime.datetime.fromtimestamp(timestamp).strftime('%A, %H:%M:%S')
myforecast = {}
for idx in range(0,40,interval):
myforecast[idx] = []
myforecast[idx].append(formatTimestamp(forecast[idx]['dt']))
myforecast[idx].append(forecast[idx]['main']['temp'])
myforecast[idx].append(forecast[idx]['main']['humidity'])
myforecast[idx].append(forecast[idx]['weather'][0]['description'])
return myforecast
myforecast = returnMyForecast(GrabForecast(),2)
for key in myforecast:
write(myforecast[key][0])
write('\n')
write(myforecast[key][1])
write(" Grad")
write('\n')
write(myforecast[key][2])
write(" {} Luftfeuchtigkeit".format("%"))
write('\n')
write(myforecast[key][3])
write('\n\n')
# Function: Reset user input vars when "back"-button on PAGE 20 is pressed
# FIXME: Input.presence is redundant
def resetInput(self,*args):
Input.presence = None
# clear entry fields
for arg in args:
arg.delete(0,"end")
# reset checkbutton variable back to False. This will also automatically change Checkbutton-relief back to raised
def resetCheckbutton(self):
for idx in range(0,len(roomie_list)):
self.frames[Page22].part_dict[idx].set(False)
# Save current debts plan as txt file
# Customize: Decide here which DebtsDict should be saved
def savePlan(self):
try:
saveDebtsTxt(normalizeDebts(valueSortedDict(conservativeDebtsDict())))
messagebox.showinfo("Zwegat Alpha","Plan gespeichert")
except:
messagebox.showwarning("Zwegat Alpha","Plan konnte nicht gespeichert werden")
# print current debts plan
def printPlan(self):
try:
printDebtsPlan()
messagebox.showinfo("Zwegat Alpha","Druckauftrag gesendet")
except:
messagebox.showwarning("Zwegat Alpha","Plan konnte nicht gedruckt werden")
# Do: Ask user for "Ok"
# Call functions based on user decision
# Note: Provide functions and their arguments as tuples
# Note: When function takes no argument provide it as a one-element tuple in pythonic fashion -> (element,)
# See: https://wiki.python.org/moin/TupleSyntax
def askOk(self,question,*funcs,cutoff):
ans = messagebox.askokcancel("Zwegat Alpha",question)
# functions to be called when ans = True
true_funcs = funcs[:cutoff]
# function to be called when ans = False
false_funcs = funcs[cutoff:len(funcs)]
def callTupleFunc(func,*args):
func(*args)
if ans == True:
for func in true_funcs:
callTupleFunc(*func)
elif ans == False:
for func in false_funcs:
callTupleFunc(*func)
def checkCriterion(self,error,*args,cutoff,criterion):
# all arguments until cutoff are variables to be evaluated
varlist = args[:cutoff]
# all arguments after cutoff are functions to be called when all variables match criterion
funcs = args[cutoff:]
# boolean that is only true when ALL variables meet criterion and is set to False when >= 1 variables don't meet criterion
gate = True