-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple-flashcards.py
258 lines (216 loc) · 9.14 KB
/
simple-flashcards.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
import os
import sys
import pathlib
from appdirs import user_data_dir
import tkinter as tk
from tkinter import ttk, filedialog
from ttkthemes import ThemedTk
import awesometkinter as atk
from awesometkinter.bidirender import add_bidi_support
from cardDeck import CardDeck
import cardParser
def resource_path(filename):
base_path = getattr(sys, '_MEIPASS',
os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, filename)
### global variables
###
def cardNumString(deck):
"""make a nice string with the current card number, e.g. 4/7"""
cardNumber = deck.get_number() + 1 # making it 1-indexed
numCards = deck.get_card_count()
return f"{cardNumber}/{numCards}"
class CardLabel(tk.Label):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
# automatically adjust the wrap to the size
# https://stackoverflow.com/a/62485627
self.bind('<Configure>', lambda e: self.config(wraplength=self.winfo_width()))
font = self.cget("font")
self.font = tk.font.nametofont('TkDefaultFont')
self.configure(font=self.font)
def get_size(self):
# multiplying by -1 is necessary here
return int(self.font.cget('size')) * -1
def set_size(self, newSize):
# multiplying by -1 is necessary here
self.font.configure(size=(newSize * -1))
class App(ThemedTk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.title("Simple Flashcards")
self.geometry('450x250')
self.iconphoto(False, tk.PhotoImage(file=resource_path('icon.gif')))
self.protocol('WM_DELETE_WINDOW', self.on_close_clicked)
self.deck = CardDeck()
self.data_dir = user_data_dir('simple-flashcards')
pathlib.Path(self.data_dir).mkdir(parents=True, exist_ok=True)
self.cardNumVar = tk.StringVar();
self.shuffled = tk.IntVar()
self.reversed = tk.IntVar()
self.addTopButtons()
ttk.Separator(self, orient='horizontal').pack(fill=tk.X)
self.mainLabel = CardLabel(self, anchor='n')
self.mainLabel.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
add_bidi_support(self.mainLabel)
self.mainLabel.set('Click Open to open a deck of flashcards.')
ttk.Separator(self, orient='horizontal').pack(fill=tk.X)
self.addStatusbar()
self.addBottomButtons()
self.setupShortcuts()
def addTopButtons(self):
topFrame = ttk.Frame(self)
ttk.Button(topFrame, text="Open",
command=self.show_filedialog).pack(side=tk.LEFT)
ttk.Button(topFrame, text="Load last file",
command=self.open_last_file).pack(side=tk.LEFT, padx=5)
ttk.Button(topFrame, text="Shortcuts",
command=self.show_shortcuts).pack(side=tk.RIGHT)
ttk.Button(topFrame, text="+", width=1,
command=self.larger_card_text).pack(side=tk.RIGHT, padx=5)
ttk.Button(topFrame, text="-", width=1,
command=self.smaller_card_text).pack(side=tk.RIGHT)
topFrame.pack(fill=tk.X)
def addStatusbar(self):
self.cardNumVar.set('0/0')
self.shuffled.set(0)
self.reversed.set(0)
statusFrame = ttk.Frame(self)
numLabel = ttk.Label(statusFrame,
textvariable=self.cardNumVar)
shuffleToggle = ttk.Checkbutton(statusFrame,
text='Shuffle', variable=self.shuffled, onvalue=1,
offvalue=0,
command=self.cardCb(self.deck.toggle_shuffle))
reverseToggle = ttk.Checkbutton(statusFrame,
text='Reverse', variable=self.reversed, onvalue=1,
offvalue=0,
command=self.cardCb(self.deck.toggle_reverse))
statusFrame.pack(fill=tk.X)
numLabel.pack(side=tk.LEFT)
shuffleToggle.pack(side=tk.RIGHT)
reverseToggle.pack(side=tk.RIGHT)
def addBottomButtons(self):
prev_btn = ttk.Button(self, text="Previous")
prev_btn['command'] = self.cardCb(self.deck.prev_card)
prev_btn.pack(side=tk.LEFT, fill=tk.X, expand=True)
flip_btn = ttk.Button(self, text="Flip over")
flip_btn['command'] = self.cardCb(self.deck.flip)
flip_btn.pack(side=tk.LEFT, fill=tk.X, expand=True)
next_btn = ttk.Button(self, text="Next")
next_btn['command'] = self.cardCb(self.deck.next_card)
next_btn.pack(side=tk.LEFT, fill=tk.X, expand=True)
def updateCardView(self):
if not self.deck.loaded: return # to preserve placeholder texts
self.mainLabel.set(self.deck.get_text())
self.cardNumVar.set(cardNumString(self.deck))
def open_last_file(self):
savePath = os.path.join(self.data_dir, "lastFilename")
if os.path.isfile(savePath):
with open(savePath, 'r') as f:
filename = f.read()
if os.path.isfile(filename):
self.open_file(filename)
return
self.safelyOpenDialog(tk.messagebox.showwarning,
title="Last file not found",
message="Last file not found. Try using Open")
def open_file(self, filename):
if filename:
fronts, backs = cardParser.from_file(filename)
if fronts is None:
# not using exceptions because try/catch is weird on tkinter
self.safelyOpenDialog(tk.messagebox.showerror,
title="Parsing error",
message="Please check the format of the flashcards file")
else:
self.shuffled.set(0)
self.reversed.set(0)
self.deck.reset()
self.deck.load_data(fronts, backs)
self.updateCardView()
savePath = os.path.join(self.data_dir, "lastFilename")
with open(savePath, 'w') as f:
f.write(filename)
def show_filedialog(self):
filename = self.safelyOpenDialog(
filedialog.askopenfilename
)
self.open_file(filename)
def smaller_card_text(self):
oldSize = self.mainLabel.get_size()
self.mainLabel.set_size(oldSize - 1)
def larger_card_text(self):
oldSize = self.mainLabel.get_size()
self.mainLabel.set_size(oldSize + 1)
def show_shortcuts(self):
entries = [
('Shortcut', 'Action'),
('----', '----'),
('j', 'Next'),
('k', 'Previous'),
('f', 'Flip over'),
('s', 'Toggle shuffle'),
('r', 'Toggle reverse'),
('+', 'Zoom in'),
('-', 'Zoom out'),
('Ctrl-o', 'Open a flashcard file'),
('Ctrl-l', 'Load last file'),
('Ctrl-h', 'Show this window'),
]
space = max([len(s[0]) for s in entries]) + 3
message = '\n'.join([f"{combination: <{space}}{meaning}" for combination, meaning in entries])
self.option_add('*Dialog.msg.font', "Monospace 10")
self.grab_set()
self.safelyOpenDialog(
tk.messagebox.showinfo,
title='Shortcuts',
message=message
)
self.option_clear()
def setupShortcuts(self):
flipVar = lambda v: v.set(1 if v.get() == 0 else 0)
def toggle_shuffle():
flipVar(self.shuffled)
self.deck.toggle_shuffle()
def toggle_reverse():
flipVar(self.reversed)
self.deck.toggle_reverse()
self.bind('<Control-o>', lambda _: self.show_filedialog())
self.bind('<Control-l>', lambda _: self.open_last_file())
self.bind('<Control-h>', lambda _: self.show_shortcuts())
self.bind('+', lambda _: self.larger_card_text())
self.bind('=', lambda _: self.larger_card_text()) # convenience
self.bind('-', lambda _: self.smaller_card_text())
self.bind('_', lambda _: self.smaller_card_text()) # convenience
self.bind('s', self.cardCb(toggle_shuffle))
self.bind('r', self.cardCb(toggle_reverse))
self.bind('j', self.cardCb(self.deck.next_card))
self.bind('k', self.cardCb(self.deck.prev_card))
self.bind('f', self.cardCb(self.deck.flip))
def cardCb(self, f):
# returns a callback function that calls "f" then updates the view
def inner(*args, **kwargs):
f()
self.updateCardView()
return inner
def safelyOpenDialog(self, dialog_function, *args, **kwargs):
# don't let root be closed before the dialog
# this is to prevent an error
self.close_enabled = False
retval = dialog_function(*args, **kwargs)
self.close_enabled = True
return retval
def report_callback_exception(self, exc, val, tb):
print(f"{exc}, {val}, {tb}")
self.safelyOpenDialog(
tk.messagebox.showerror,
title='Error',
message=f'An error occurred: {exc.__name__}'
)
def on_close_clicked(self):
if getattr(self, 'close_enabled', True):
self.destroy()
if __name__ == '__main__':
window = App(theme='breeze')
window.mainloop()