-
Notifications
You must be signed in to change notification settings - Fork 2
/
gui.py
executable file
·1653 lines (1424 loc) · 63.9 KB
/
gui.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 python3.4
import redditpaper as rp
# must insert config here, so that it
# works throughout both modules with onetime
# setup
rp.Config_logging()
import webbrowser
import os
import subprocess
import time
import threading
from tkinter import *
from tkinter import font
from tkinter import StringVar
from tkinter import ttk
from PIL import Image
from praw import errors
class Application(Tk):
width = 525
height = 555
def __init__(self, master=None):
Tk.__init__(self, master)
# set title of application on titlebar
self.wm_title("Reddit Paper")
# set theme
theme = ttk.Style()
theme.theme_use('clam')
# set up frame to hold widgets
root = Frame(self) # background="bisque")
root.pack(side = "top", fill = "both", expand = True)
# set minsize of application
self.setUpWindow()
# set docked icon in system tray
self.addIcon()
# adds buttons and status bar for main page
self.buttons = AddButtons(root, self)
StatusBar(master)
# window used to pack the pages into
self.window = Frame(root)#bg = "cyan")
self.window.pack()
self.pages = {}
for F in (CurrentImg, PastImgs, Settings, About):
frame = F(self.window, self)
self.pages[F] = frame
frame.grid(row = 0, column = 0, sticky = "nsew")
# frame to show on startup
self.show_frame(CurrentImg)
def show_frame(self, page):
"""
Input: the page to display
Output: displays the page selected on button click
"""
frame = self.pages[page]
# sets the focus on the itemFrame when the
# PastImgs button is clicked so that the
# list of pictures is scrollable
if page is PastImgs:
try:
frame.canvas.focus_set()
# Throws attribute error and also a _tkinter.TclError
# which isn't a valid keyword for some reason
except:
rp.log.debug("Could not set focus to PastImgs, likely due to "
"itemFrame not being available", exc_info = True)
# all images are likely deleted from
# the itemFrame
pass
self.setButtonImages(page)
frame.tkraise()
def setButtonImages(self, page):
"""
Sets the button images for the top of the program to change
background color depending on which page is active
"""
# images named by past image (p), currentimg (c),
# about (a), settings (s), and then whether it will
# be clicked (_c) or unclicked (_u)
self.c_c = PhotoImage(file = './images/c_c.png')
self.c_u = PhotoImage(file = './images/c_u.png')
self.p_c = PhotoImage(file = './images/p_c.png')
self.p_u = PhotoImage(file = './images/p_u.png')
self.s_c = PhotoImage(file = './images/s_c.png')
self.s_u = PhotoImage(file = './images/s_u.png')
self.a_c = PhotoImage(file = './images/a_c.png')
self.a_u = PhotoImage(file = './images/a_u.png')
# if page is clicked, set that image to be '_c' (clicked)
# and set all other pages to be 'unclicked'
if page is CurrentImg:
self.buttons.c.config(image = self.c_c)
self.buttons.p.config(image = self.p_u)
self.buttons.s.config(image = self.s_u)
self.buttons.a.config(image = self.a_u)
elif page is PastImgs:
# past images page
self.buttons.c.config(image = self.c_u)
self.buttons.p.config(image = self.p_c)
self.buttons.s.config(image = self.s_u)
self.buttons.a.config(image = self.a_u)
elif page is Settings:
# settinsg page
self.buttons.c.config(image = self.c_u)
self.buttons.p.config(image = self.p_u)
self.buttons.s.config(image = self.s_c)
self.buttons.a.config(image = self.a_u)
else:
# about page
self.buttons.c.config(image = self.c_u)
self.buttons.p.config(image = self.p_u)
self.buttons.s.config(image = self.s_u)
self.buttons.a.config(image = self.a_c)
def addIcon(self):
self.img = PhotoImage(file = 'images/rp_sq.png')
self.tk.call('wm', 'iconphoto', self._w, self.img)
def setUpWindow(self):
"""
Aligns the GUI to open in the middle
of the screen(s)
credit: https://stackoverflow.com/questions/
14910858/how-to-specify-where-a-tkinter-window-opens
"""
ws = self.winfo_screenwidth()
hs = self.winfo_screenheight()
self.x = (ws//2) - (self.width//2)
self.y = (hs//2) - (self.height//2)
self.minsize(width = self.width, height = self.height)
self.maxsize(width = self.width, height = self.height)
self.geometry('{}x{}+{}+{}'.format(self.width, self.height,
self.x, self.y))
###############################################################################
class AboutInfo():
"""
Information about the GUI version, links to static sites (reddit,
and PayPal), and author name and information
"""
_version = "1.0"
_author = "Cameron Gagnon"
_email = "[email protected]"
_redditAcct = "https://www.reddit.com/message/compose/?to=camerongagnon"
_payPalAcct = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&"\
"business=PKYUCH3L9HJZ6&lc=US&item_name=Cameron%20Gagnon"\
"&item_number=81140022¤cy_code=USD&bn=PP%2dDonations"\
"BF%3abtn_donateCC_LG%2egif%3aNonHosted"
_github = "https://github.com/cameron-gagnon/reddit-paper"
_subreddit = "https://www.reddit.com/r/reddit_paper"
def version():
return AboutInfo._version
def author():
return AboutInfo._author
def reddit():
return AboutInfo._redditAcct
def subreddit():
return AboutInfo._subreddit
def PayPal():
return AboutInfo._payPalAcct
def email():
return AboutInfo._email
def GitHub():
return AboutInfo._github
################################################################################
class Fonts():
_VERDANA = "Verdana"
_CURSOR = "hand2"
_HYPERLINK = "#0000EE"
_XL = 16
_L = 12
_M = 10
_S = 8
_XS = 7
_H1 = 25
def XS():
xs = font.Font(family = Fonts._VERDANA, size = Fonts._XS)
return xs
def XS_U():
xs_u = font.Font(family = Fonts._VERDANA, size = Fonts._XS,
underline = True)
return xs_u
def S():
s = font.Font(family = Fonts._VERDANA, size = Fonts._S)
return s
def S_U():
s_u = font.Font(family = Fonts._VERDANA, size = Fonts._S,
underline = True)
return s_u
def M():
m = font.Font(family = Fonts._VERDANA, size = Fonts._M)
return m
def M_U():
med_u = font.Font(family = Fonts._VERDANA, size = Fonts._M,
underline = True)
return med_u
def L():
l = font.Font(family = Fonts._VERDANA, size = Fonts._L)
return l
def L_U():
l_u = font.Font(family = Fonts._VERDANA, size = Fonts._L,
underline = True)
return l_u
def XL():
xl = font.Font(family = Fonts._VERDANA, size = Fonts._XL)
return xl
def XL_U():
xl_u = font.Font(family = Fonts._VERDANA, size = Fonts._XL,
underline = True)
return xl_u
def H1():
h1 = font.Font(family = Fonts._VERDANA, size = Fonts._H1)
return h1
def H1_U():
h1_u = font.Font(family = Fonts._VERDANA, size = Fonts._H1,
underline = True)
return h1_u
######################## Classes for Messages #################################
class Message(Toplevel):
def __init__(self, master, title):
"""
Creates popup as Toplevel() and sets its title in the window
"""
Toplevel.__init__(self, master)
#self.popup = Toplevel()
self.wm_title(title)
self.addIcon('images/rp_sq.png')
self.set_dimensions(master, 400, 400)
self.inner_frame = Frame(self, width = 400, height = 400)
self.inner_frame.pack()
# self.pack_button()
# bit of a hack to ensure that the window has grab_set applied to it
# this is because the window may not be there when self.grab_set() is
# called, so we wait until it happens without an error
while True:
try:
self.grab_set()
except TclError:
pass
else:
break
def set_dimensions(self, master, w, h):
"""
Sets the position and size on screen for the popup
"""
x = master.winfo_rootx()
y = master.winfo_rooty()
x = (Application.width // 2) + x - (w // 2) - 10
y = (Application.height // 2) + y - 405
# set permanent dimensions of popup
self.minsize(width = w, height = h)
self.maxsize(width = w, height = h)
self.geometry('{}x{}+{}+{}'.format(w, h, x, y))
def delete(self):
"""
Destroys the popup
"""
self.grab_release()
self.destroy()
def pack_label(self, text, pady = 8, font = None, anchor = "center",
justify = None):
"""
Packs a label into the popup with the specified text
"""
# bit of a hack since Fonts.L() throws an error if present in the
# function declaration
if not font:
font = Fonts.M()
label = ttk.Label(self.inner_frame, anchor = anchor,
text = text, wraplength = 420,
font = font, justify = justify)
label.pack(side = "top", fill = "x", pady = pady)
def pack_button(self, pady = (10, 10)):
"""
Place a button at the bottom of the widget with the text "Okay"
"""
b = ttk.Button(self.inner_frame, text = "Okay", command = self.delete)
b.pack(side = "bottom", pady = pady)
def addIcon(self, file_name):
"""
Adds an error icon to the popup box
"""
self.img = PhotoImage(file = file_name)
self.tk.call('wm', 'iconphoto', self._w, self.img)
class ErrorMsg(Message):
def __init__(self, master, text, title = "Error!"):
popup = Message.__init__(self, master, title)
length = 0
height = 0
self.addIcon('images/error.png')
if isinstance(text, list):
if len(text) == 1:
# if string, return length of string
length = len(text[0])
height = 130
height += length // 60 * 15
rp.log.debug("Length of error string is: {}, "
"and height is: {}".format(length, height))
elif len(text) > 1:
# find max length of string in the list of errors
length = len(max(text))
# length of the list is num of elts in list
# so to get the height, we take this and
# multiply it by a constant and add a base amount
height = len(text) * 25 + 130
height += length // 60 * 20
rp.log.debug("Length of max error string is: {} "
"and height is {}".format(length, height))
else:
# no errors in CLArgs
pass
self.pack_label("Invalid Argument(s):")
else:
# if just a regular string that we want an error message
length = len(text)
height = 125
height += len(text) // 60 * 15
self.pack_label("Invalid Argument(s):")
self.pack_label(text)
rp.log.debug("Length of error string is: {}, "
"and height is: {}".format((length, height)))
#length * 5 because each char is probably
# about 5 px across. + 160 for padding
width = length * 5 + 160
if (length * 5 + 160) > 475:
width = 475
rp.log.debug("Width of ErrorMsg is {}".format(width))
rp.log.debug("Height of ErrorMsg is {}".format(height))
self.set_dimensions(master, width, height)
self.pack_button()
class InvalidArg(ErrorMsg):
def __init__(self, master, text):
"""
Used spcecifically to display the CLArguments
"""
ErrorMsg.__init__(self, master, text)
if len(text) > 1:
for string in text:
self.pack_label(string)
elif len(text) == 1:
self.pack_label(text[0])
else:
rp.log.debug("No errors in CLArgs")
class ConfirmMsg(Message):
def __init__(self, master):
"""
Pop up box/message for confirmation of settings/deleting settings
"""
Message.__init__(self, master, "Confirm!")
width = 180
height = 75
self.set_dimensions(master, width, height)
self.pack_label("Are you sure?")
BFrame = Frame(self)
BFrame.pack()
B1 = ttk.Button(BFrame, text = "Yes", width = 8, command = lambda: master.del_sel(self))
B1.pack_propagate(0)
B2 = ttk.Button(BFrame, text = "No", width = 8, command = self.delete)
B2.pack_propagate(0)
B1.pack(side = "left", padx = (0, 5))
B2.pack(side = "left")
class AutoScrollbar(ttk.Scrollbar):
# a scrollbar that hides itself if it's not needed. only
# works if you use the grid geometry manager.
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
# grid_remove is currently missing from Tkinter!
self.tk.call("grid", "remove", self)
else:
self.grid(sticky = 'nsew')
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise Exception("cannot use pack with this widget")
def place(self, **kw):
raise Exception("cannot use place with this widget")
class ImageFormat():
def strip_file_ext(self, image_name):
"""
Used to remove the .jpg or other ending from im.image_name
so that we can resave the thumbnail with .png
"""
index = image_name.rfind('.')
im_name = image_name[:index]
return im_name
def add_png(self, image_name):
"""
Appends the .png to the end of im.image_name to save the
thumbnail with .png
"""
im_name = image_name + ".png"
return im_name
class StatusBar(Frame):
def __init__(self, master):
Frame.__init__(self, master)
"""
Represents the statusbar at the bottom of the application.
The statusbar is set up in AddButtons()
It reads from the settings.conf file to get the statusbar
text and then updates accordingly.
Executes after every second.
"""
# statusbar for bottom of application
self.text = StringVar()
self.text.set(rp.Config.statusBar())
self.statusBar = ttk.Label(master, text = self.text.get(), border=1,
relief = SUNKEN, anchor = "w")
# pack the labels/frame to window
self.statusBar.pack(side = "bottom", fill = "x", anchor = "w")
self.setText()
def setText(self):
"""
Sets the text of the status bar to the string in the
config file 'settings.conf'
"""
text = rp.Config.statusBar()
if text == self.text:
pass
else:
self.text = text
self.statusBar.config(text = self.text)
self.after(1000, lambda: self.setText())
###############################################################################
class AddButtons(Frame):
def __init__(self, master, cls):
Frame.__init__(self, master)
self.topbar = Frame(master)#bg="red")
# current image button
self.cphoto = PhotoImage(file="./images/c_c.png")
self.c = Button(self.topbar, image = self.cphoto,
width = 125, height = 125, cursor = Fonts._CURSOR,
command = lambda: cls.show_frame(CurrentImg))
self.c.grid(row = 0, column = 0, sticky = "N")
# past image button
self.pphoto = PhotoImage(file="./images/p_u.png")
self.p = Button(self.topbar, image = self.pphoto,
width = 125, height = 125, cursor = Fonts._CURSOR,
command = lambda: cls.show_frame(PastImgs))
self.p.grid(row = 0, column = 1, sticky = "N")
# settings buttons
self.sphoto = PhotoImage(file="./images/s_u.png")
self.s = Button(self.topbar, image = self.sphoto,
width = 125, height = 125, cursor = Fonts._CURSOR,
command = lambda: cls.show_frame(Settings))
self.s.grid(row=0, column = 2, sticky = "N")
# about buttons
self.aphoto = PhotoImage(file="./images/a_u.png")
self.a = Button(self.topbar, image = self.aphoto,
width = 125, height = 125, cursor = Fonts._CURSOR,
command = lambda: cls.show_frame(About))
self.a.grid(row = 0, column = 3, sticky = "N")
self.topbar.pack(side = "top")
# **** Current Image Page **** #
# Shows a thumbnail of the current image set as the
# background, with a link to that submission.
class CurrentImg(Frame, ImageFormat):
TIMER = 3000
def __init__(self, parent, controller):
"""
Packs the frames needed, and initiaties
the updateFrame to continuously call itself
"""
Frame.__init__(self, parent)
# pack frames/labels
self.frame = Frame(self, width = 525, height = 400)#, bg = "#969696") #bg = "magenta")
self.frame.pack_propagate(0)
self.frame.pack()
self.get_past_img(parent)
self.updateTimer()
self.updateFrame(parent)
def open_link(self, link):
"""
Opens the link provided in the default
webbrowser
"""
webbrowser.open_new(link)
def get_past_img(self, parent):
"""
looks up the most recent wallpaper set based on the
config file and passes that info to set_past_img
"""
self.image_name = rp.Config.lastImg()
if self.image_name:
rp.log.debug("Last Wallpaper is: %s" % self.image_name)
try:
im = rp.DBImg(self.image_name)
im.link
self.set_past_img(im)
# AttributeError is in case the image returned
# is incomplete
except (AttributeError, TypeError):
rp.log.debug("Attribute Error in get_past_img")
else:
rp.log.debug("No image set as last image in settings.conf")
def set_past_img(self, im):
"""
Creates the inner frame within the main frame of
CurrentImg and packs the picture thumbnail and title
into it.
"""
# create subframe to pack widgets into, then destroy it
# later
self.image_name = im.image_name
self.subFrame = Frame(self.frame, width = 525, height = 410)
self.subFrame.pack_propagate(0)
self.subFrame.pack()
font_to_use = Fonts.L_U()
# set font to be smaller if title is too long
if len(im.title) > 150:
font_to_use = Fonts.M_U()
# create title link
self.linkLabel = ttk.Label(self.subFrame,
text = im.title,
font = font_to_use,
justify = 'center',
foreground = Fonts._HYPERLINK,
cursor = Fonts._CURSOR,
wraplength = 500)
self.linkLabel.pack(pady = (35, 10), padx = 10)
self.linkLabel.bind("<Button-1>", lambda event: self.open_link(im.post))
try:
# create image and convert it to thumbnail
with open(im.save_location, 'rb') as image_file:
imThumb = Image.open(image_file)
im.strip_file_ext()
im.updateSaveLoc()
imThumb.thumbnail((400, 250), Image.ANTIALIAS)
imThumb.save(im.thumb_save_loc_C, "PNG")
# apply photolabel to page to display
self.photo = PhotoImage(file = im.thumb_save_loc_C)
self.photoLabel = ttk.Label(self.subFrame, image = self.photo)
self.photoLabel.pack(side = "bottom", expand = True)
except FileNotFoundError:
pass
def delSubframe(self):
"""
Clears up the widgets that are in the frame of the main
CurrentImg, so that we can reset all the widgets
"""
try:
self.photoLabel.destroy()
self.linkLabel.destroy()
self.subFrame.destroy()
except AttributeError:
# happens when no image is set at first run of program
pass
def updateFrame(self, parent):
"""
Calls itself to update the frame every self.TIMER
to update the past image if it has changed
"""
if self.image_name != rp.Config.lastImg():
self.updateTimer()
self.delSubframe()
self.get_past_img(parent)
try:
self.after(self.TIMER, lambda: self.updateFrame(parent))
except AttributeError:
# happens when settings.conf is not created yet
pass
def updateTimer(self):
try:
HR, MIN = rp.Config.cycletime()
# converts hours and min to milliseconds
# to be used by the tkinter after() fn
self.TIMER = int(HR * 3600000 + MIN * 60000)
except ValueError:
# happens when settings.conf is not created yet
pass
def __str__(self):
return "Current Image"
# **** Past Images Page **** #
# Gives a listing of past submissions, with a smaller thumbnail of the image
# and the title/resolution of the images.
# Includes: * checkboxes to delete the images selected
# * Scrollable list of all images downloaded/used in the past
class PastImgs(Frame, ImageFormat):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
# select all box
self.selVar = BooleanVar()
self.selVar.set(False)
self.selVar.trace('w', lambda e, x, y: self.change_all(e))
selectBox = ttk.Checkbutton(self, text = "Select all", variable = self.selVar)
selectBox.pack(anchor = 'w', pady = (15, 2), padx = (35, 10))
### begin canvas/frame/picture list
self.picFrame = Frame(self, width = 450, height = 300)
self.picFrame.grid_rowconfigure(0, weight = 1)
self.picFrame.grid_columnconfigure(0, weight = 1)
self.picFrame.pack()
self.canvas = Canvas(self.picFrame, width = 450, height = 300)
self.canFrame = Frame(self.canvas)
self.canvas.create_window((0,0), window = self.canFrame, anchor = 'nw')
self.canvas.pack(side="left")
self.setScroll()
# POPULATE CANVAS WITH IMAGES!!!!!!!!
self.picList = self.findSavedPictures()
# these lists save each checkbox and frame/photo so we can
# identify them later when they need to be destroyed
self.frames = []
self.already_deleted = []
self.itemFrame = []
picThread = threading.Thread(target=self.populate,
args=(self.canFrame, self.picList))
picThread.start()
# self.populate(self.canFrame, self.picList)
# bottom frame for buttons
self.bottomFrame = Frame(self)
self.delete = ttk.Button(self.bottomFrame, text = "Delete selected",
state = "normal",
command = lambda: ConfirmMsg(self))
# 'delete all' button 'delete selected' button
self.delete.pack(side = "right", padx = (0, 3))
# packs the frame that holds the delete buttons
self.bottomFrame.pack(side = "bottom", anchor = "e",
pady = (0, 15), padx = (0, 27))
### end canvas/frame/picture list
self.updatePastImgs()
def setScroll(self):
# create frame to hold scrollbar so we can
# use grid on the scrollbar
try:
self.scrollFrame.destroy()
except:
# no scrollbar yet created
pass
self.scrollFrame = Frame(self.picFrame)
# set rows and column configures so we can
# make scrollbar take up entire row/column
self.scrollFrame.rowconfigure(1, weight = 1)
self.scrollFrame.columnconfigure(1, weight = 1)
self.scroll = AutoScrollbar(self.scrollFrame,
orient = "vertical",
command = self.canvas.yview)
# set scrollbar as callback to the canvas
self.canvas.configure(yscrollcommand = self.scroll.set)
# set the scrollbar to be the height of the canvas
self.scroll.grid(sticky = 'ns', row = 1, column = 0)
# set the scrollbar to be packed on the right side
self.scrollFrame.pack(side="right", fill="y")
# bind the picture frame to the canvas
self.picFrame.bind("<Configure>", self.setFrame)
self.setFrame()
def setFrame(self, event = None):
""" Sets the canvas dimensions and the scroll area """
self.canvas.configure(scrollregion = self.canvas.bbox('all'))
def setKeyBinds(self, widget):
"""
Sets the binds to the keys for the canvas movements
when adding new elts
"""
widget.bind("<Button-4>", self.onMouseWheel)# up scroll
widget.bind("<Button-5>", self.onMouseWheel)# down scroll
widget.bind("<Up>", self.onMouseWheel)
widget.bind("<Down>", self.onMouseWheel)
def onMouseWheel(self, event):
"""
Scrolls the canvas up or down depending on the
event entered (arrow keys/mouse scroll)
"""
keyNum = {116 : 1, # Down arrow key
111 : -1} # Up arrow key
scrollNum = {4 : -1,
5 : 1}
scrollVal = None
# up/down arrows
if event.keycode in keyNum:
scrollVal = keyNum.get(event.keycode)
# scroll wheel events
elif event.num in scrollNum:
scrollVal = scrollNum.get(event.num)
self.canvas.yview_scroll(scrollVal, "units")
def change_all(self, event):
"""
selects/deselects all the pictures (to be deleted)
"""
if self.selVar.get():
self.selVar.set(True)
for box in self.frames:
box[0].set(True)
else:
self.selVar.set(False)
for box in self.frames:
box[0].set(False)
def del_sel(self, popup):
"""
Delete all frames that have their checkbox
checked.
self.frames[i][2] ## image class
self.frames[i][2].save_location
## file path to original img
'/path/to/file/jkY32rv.jpg'
self.frames[i][2].thumb_save_loc_P
## file path to _P.png thumbnail
'/path/to/file/jkY32rv_P.png'
self.frames[i][2].thumb_save_loc_C
## file path to _C.png thumbnail
'/path/to/file/jkY32rv_C.png'
self.frames[i][2].image_name ## original img name 'jkY32rv.jpg'
self.frames[i][0] ## checkbox var
self.frames[i][1] ## frame to destroy
"""
# create copy so we don't modify a list as we
# loop over it
to_check_list = self.frames[:]
i = 0
for frame in to_check_list:
# if the checkbox var is True
if frame[0].get() and len(self.picList):
# deletes frame from canvas
try:
rp.log.debug("i is: {} frames len: {} picList len: {}".format(i, len(self.frames), len(self.picList)))
#print(self.frames)
#print(self.picList)
rp.log.debug("CANFRAME IS: {}".format(self.canFrame.winfo_height()))
to_del = self.frames.pop(i)
rp.log.debug("LEN OF FRAME IS NOW: {}".format(len(self.frames)))
rp.log.debug("Popping: {}".format(self.picList[i].image_name))
self.picList.pop(i)
rp.log.debug("LEN OF PICLIST IS NOW: {}".format(len(self.picList)))
item = self.itemFrame.pop(i)
# delete visible frame
#to_del[1].des
item.destroy()
# reset scrollbar
self.scroll.destroy()
self.scrollFrame.destroy()
self.setScroll()
except AttributeError:
# occurs when a frame is supposed to be present
# but actually isn't
rp.log.debug("Frame isn't present", exc_info = True)
to_del_img = to_del[2]
try:
rp.log.debug("to_del P: %s" % to_del_img.thumb_save_loc_P)
rp.log.debug("to_del C: %s" % to_del_img.thumb_save_loc_C)
rp.log.debug("to_del : %s" % to_del_img.save_location)
# delete thumbnail_P
os.remove(to_del_img.thumb_save_loc_P)
rp.log.debug("Removed to_del_P")
# delete original file
os.remove(to_del_img.save_location)
rp.log.debug("Removed to_del")
# delete database entry
rp.Database.del_img(to_del_img.image_name)
# add to_del_img.image_name to list so we don't
# add it again
self.already_deleted.append(to_del_img.image_name)
try:
os.remove(to_del_img.thumb_save_loc_C)
rp.log.debug("Removed to_del_C: %s" % to_del_img.thumb_save_loc_C)
except FileNotFoundError:
# image was likely not set as current image, may not
# have been correct dimensions
rp.log.debug("It appears that the image %s was never "
"set as a current image" % to_del_img.thumb_save_loc_C)
except (OSError, FileNotFoundError):
rp.log.debug("File not found when deleting", exc_info = True)
rp.log.debug(to_del_img.image_name)
else:
i += 1
self.setFrame()
self.scroll.destroy()
self.setScroll()
self.selVar.set(False)
# don't forget to destroy the popup!
popup.destroy()
def remove_C(self, photoPath, photo):
"""
Formats the photo name so that the photo name is
the %PHOTONAME%_C.png and then prepend the file path
to the photo, as it does not contain the path
"""
# take the .png off, add _C to it, then add .png
# back on
imageC = self.strip_file_ext(photo)
imageC += "_C"
imageC = self.add_png(imageC)
# retrieves the download location based on
# other image
index = photoPath.rfind('/') + 1
path = photoPath[:index]
imageC = path + imageC
return imageC
def populate(self, frame, picList):
"""
Fill the frame with more frames of the images
"""
rp.log.debug("Len of picList to populate is {}".format(len(picList)))
for i, im in enumerate(picList):
rp.log.debug("I IS FRESH AND IS {}".format(i))
try:
rp.log.debug("IMAGE SAVE LOC IS: {}".format(im.save_location))
with open(im.save_location, 'rb') as image_file:
# create and save image thumbnail
# PIL module used to create thumbnail
imThumb = Image.open(image_file)
im.strip_file_ext()
im.updateSaveLoc()
imThumb.thumbnail((50, 50), Image.ANTIALIAS)
imThumb.save(im.thumb_save_loc_P, "PNG")
except (FileNotFoundError, OSError):
# usually a file that is not an actual image, such
# as an html document
rp.log.debug("ERROR IS:", exc_info = True)
rp.log.debug("FILE NOT FOUND, OR OS ERROR, I is {}".format(i))
i -= 1
rp.log.debug("I SUBTRACTED {}".format(i))
continue
# create frame to hold information for one picture
item = Frame(frame, width = 450, height = 50)
# self.picList has already been appended to before those pictures
# that were appended were gridded. Therefore, we subtract the len
# of the new images we are adding, since that will give us the
# row of the last image that was added, and then we add our current
# index to this so we arrive at the latest unoccupied row
len_p_list = len(self.picList)
len_list = len(picList)
# only change the row if the p_list is a
# different length of len_list
if (len_p_list - len_list) != 0:
rp.log.debug("I WAS {}".format(i))
i += (len_p_list - len_list)
rp.log.debug("UPDATING I INDEX to {}".format(i))
rp.log.debug("I is now {}".format(i))
item.grid(row = i, column = 0)
#rp.log.debug("LEN of item frame before append: ", len(self.itemFrame))
self.itemFrame.append(item)
#rp.log.debug("LEN OF ITEM FRAME IN POPULATE: ", len(self.itemFrame))
item.pack_propagate(0)
# checkbox to select/deselect the picture
checkVar = BooleanVar(False)
check = ttk.Checkbutton(item,
variable = checkVar)
check.pack(side = "left", padx = 5)
# insert the thumbnail and make the frame have a minimum w/h so
# that the im.title won't slide over to the left and off-center
# itself
photo = PhotoImage(file = im.thumb_save_loc_P)
photoFrame = Frame(item, width = 75, height = 50)
photoFrame.pack_propagate(0)
photoLabel = ttk.Label(photoFrame, image = photo)
photoFrame.pack(side = "left")
photoLabel.image = photo # keep a reference per the docs!
photoLabel.pack(side = "left", padx = 10)
# text frame
txtFrame = Frame(item)
txtFrame.pack()