-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVisualNxGUI.py
More file actions
676 lines (541 loc) · 25.3 KB
/
VisualNxGUI.py
File metadata and controls
676 lines (541 loc) · 25.3 KB
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
#!/usr/bin/env python3
"""
=======
ScaleNx
=======
------------------------
Visual GUI ScaleNx shell
------------------------
**VisualNxGUI.py** is a visual GUI shell for `ScaleNx`_ module.
Unlike main GUI shell, ScaleNxGUI.py, it is equipped with preview widget
and allows fast switching between scaling algorithms to compare result,
and previewing scaling result before saving (or not saving) it.
Beware that "fast switching" may be quite slow for a big image. Also
remember that generating preview takes additional CPU time and, most important,
memory; therefore it is **not recommended** to use VisualNxGUI.py
**for big images**.
Use ScaleNxGUI.py for big images instead.
File formats
------------
Input: PNG, PPM, PGM, PBM.
Output: PNG, PPM, PGM.
History:
--------
25.10.20.14 Initial version of ScaleNx host with preview - 20 Oct 2025.
25.11.7.1 Release 7 Nov 2025.
26.1.14.6 Suitable filter execution time display added to info string.
Result may be copied to clipboard on info string Ctrl+Click.
26.1.20.22 Extended zoom out range for big images.
26.1.26.1 Cleansing and harmonization.
26.2.11.19 Changes to new ScaleNx import structure reduced code length.
----
Main site: `The Toad's Slimy Mudhole`_
.. _The Toad's Slimy Mudhole: https://dnyarri.github.io
`ScaleNx`_ explanations and illustrations page.
.. _ScaleNx: https://dnyarri.github.io/scalenx.html
ScaleNx Git repositories: `ScaleNx@Github`_, `ScaleNx@Gitflic`_.
.. _ScaleNx@Github: https://github.com/Dnyarri/PixelArtScaling
.. _ScaleNx@Gitflic: https://gitflic.ru/project/dnyarri/pixelartscaling
"""
__author__ = 'Ilya Razmanov'
__copyright__ = '(c) 2025-2026 Ilya Razmanov'
__credits__ = 'Ilya Razmanov'
__license__ = 'unlicense'
__version__ = '26.2.18.0'
__maintainer__ = 'Ilya Razmanov'
__email__ = 'ilyarazmanov@gmail.com'
__status__ = 'Development'
from copy import deepcopy
from pathlib import Path
from random import randbytes # Used for random icon only
from time import ctime, time
from tkinter import Button, Frame, Label, Menu, Menubutton, OptionMenu, PhotoImage, StringVar, Tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
from tkinter.messagebox import showinfo
from pypng.pnglpng import list2png, png2list
from pypnm.pnmlpnm import list2bin, list2pnm, pnm2list
from scalenx import scaleNx # Configurable ScaleNx as of 2026.2.11.19
""" ╔══════════════════════════════════╗
║ GUI events and functions thereof ║
╚══════════════════════════════════╝ """
def DisMiss(event=None) -> None:
"""Kill dialog and continue."""
sortir.destroy()
def ShowMenu(event) -> None:
"""Pop menu up (or sort of drop it down)."""
menu02.post(event.x_root, event.y_root)
def ShowInfo(event=None) -> None:
"""Show image information."""
file_size = Path(sourcefilename).stat().st_size
file_size_str = f'{file_size / 1048576:.2f} Mb' if (file_size > 1048576) else f'{file_size / 1024:.2f} Kb' if (file_size > 1024) else f'{file_size} bytes'
showinfo(
title='Image information',
message=f'File properties:\nLocation: {sourcefilename}\nSize: {file_size_str}\nLast modified: {ctime(Path(sourcefilename).stat().st_mtime)}',
detail=f'Image properties, as represented internally:\nStatus: {is_filtered=}, {is_saved=}\nWidth: {X} px\nHeight: {Y} px\nChannels: {Z} channel{"s" if Z > 1 else ""}\nColor depth: {maxcolors + 1} gradations/channel',
)
def UINormal() -> None:
"""Normal UI state, buttons enabled."""
method_menu['state'] = 'normal'
info00['state'] = 'normal'
info_string.config(text=info_normal['txt'], foreground=info_normal['fg'], background=info_normal['bg'])
sortir.update()
def UIBusy() -> None:
"""Busy UI state, buttons disabled."""
method_menu['state'] = 'disabled'
info00['state'] = 'disabled'
info_string.config(text=info_busy['txt'], foreground=info_busy['fg'], background=info_busy['bg'])
sortir.update()
def ShowPreview(preview_name: PhotoImage, caption: str) -> None:
"""Show preview_name PhotoImage with caption below."""
global zoom_factor, preview
preview = preview_name
if zoom_factor > 0:
preview = preview.zoom(zoom_factor + 1)
label_zoom['text'] = f'Zoom {zoom_factor + 1}:1'
elif zoom_factor < 0:
preview = preview.subsample(1 - zoom_factor)
label_zoom['text'] = f'Zoom 1:{1 - zoom_factor}'
else:
preview = preview_name
label_zoom['text'] = 'Zoom 1:1'
zanyato.config(text=caption, font=('helvetica', 8), image=preview, compound='top', padx=0, pady=0, justify='center', background=zanyato.master['background'], relief='flat', borderwidth=1, state='normal')
zanyato.pack_configure(pady=max(0, 16 - (preview.height() // 2)))
def GetSource(event=None) -> None:
"""Open source image and redefine other controls state."""
global zoom_factor, view_src, is_filtered, is_saved, info_normal, color_mode_str, operation, timing
global preview, preview_src, preview_filtered # preview and copies of preview
global sourcefilename, X, Y, Z, maxcolors, source_image, info
global result_image
operation = 'Opening'
# ↓ Temporary saving info in case of "Open.." cancel
old_sourcefilename = sourcefilename
# ↓ Opening "Open.." dialog
sourcefilename = askopenfilename(title='Open image file', filetypes=[('Supported formats', '.png .ppm .pgm .pbm .pnm'), ('Portable network graphics', '.png'), ('Portable any map', '.ppm .pgm .pbm .pnm')])
if sourcefilename == '':
sourcefilename = old_sourcefilename
return
# ↓ Next must be set AFTER "sourcefilename", in case of "Open.." cancel
zoom_factor = 0
view_src = True
is_filtered = is_saved = False
UIBusy()
start = time()
if Path(sourcefilename).suffix.lower() == '.png':
# ↓ Reading PNG image as list
X, Y, Z, maxcolors, source_image, info = png2list(sourcefilename)
elif Path(sourcefilename).suffix.lower() in ('.ppm', '.pgm', '.pbm', '.pnm'):
# ↓ Reading PNM image as list
X, Y, Z, maxcolors, source_image = pnm2list(sourcefilename)
# ↓ Creating dummy info required to correctly Save As PNG later.
# Fixing color mode, the rest is fixed with pnglpng v. 25.01.07.
info = {'bitdepth': 16} if maxcolors > 255 else {'bitdepth': 8}
else:
raise ValueError('Extension not recognized')
timing = time() - start
""" ┌────────────────────────────────────────────┐
│ Creating deep copy of source 3D list │
│ to avoid accumulating repetitive filtering │
└────────────────────────────────────────────┘ """
result_image = deepcopy(source_image)
""" ┌───────────────┐
│ Viewing image │
└───────────────┘ """
# ↓ Converting list to bytes of PNM-like structure "preview_data" in memory
preview_data = list2bin(result_image, maxcolors, show_chessboard=True)
# ↓ Now generating preview from "preview_data" bytes using Tkinter
preview = PhotoImage(data=preview_data)
# ↓ Finally the show part
ShowPreview(preview, 'Source')
""" ┌─────────────────────────────────────────────┐
│ Creating copy of source preview for further │
│ switch between source and result │
└─────────────────────────────────────────────┘ """
preview_src = preview_filtered = preview
# ↓ Attempt to zoom to fit. Singe zoomOut() must fit for a reasonable image size.
# GUI X extra = 8 px, GUI Y extra = 150 px
if X + 16 > sortir.winfo_screenwidth() or Y + 152 > sortir.winfo_screenheight():
zoomOut()
# ↓ binding on preview click
zanyato.bind('<Control-Button-1>', zoomIn) # Ctrl + left click
zanyato.bind('<Double-Control-Button-1>', zoomIn) # Ctrl + left click too fast
zanyato.bind('<Control-+>', zoomIn)
zanyato.bind('<Control-=>', zoomIn)
zanyato.bind('<Alt-Button-1>', zoomOut) # Alt + left click
zanyato.bind('<Double-Alt-Button-1>', zoomOut) # Alt + left click too fast
zanyato.bind('<Control-minus>', zoomOut)
zanyato.bind('<Control-Key-1>', zoomOne)
zanyato.bind('<Control-Alt-Key-0>', zoomOne)
sortir.bind_all('<MouseWheel>', zoomWheel) # Wheel scroll
sortir.bind_all('<Control-i>', ShowInfo)
menu02.entryconfig('Image Info...', state='normal')
# ↓ binding global
sortir.bind_all('<Return>', RunFilter)
# ↓ resetting menu to "None" for every image
method_str.set('None')
# ↓ enabling save
menu02.entryconfig('Save as...', state='normal')
sortir.bind_all('<Control-Shift-S>', SaveAs)
# ↓ enabling zoom buttons
butt_plus.config(state='normal', cursor='hand2')
butt_minus.config(state='normal', cursor='hand2')
# ↓ Adding filename, mode and status to window title a-la Photoshop
if Z == 1:
color_mode_str = f' (L:{"8" if maxcolors < 256 else "16"})'
elif Z == 2:
color_mode_str = f' (LA:{"8" if maxcolors < 256 else "16"})'
elif Z == 3:
color_mode_str = f' (RGB:{"8" if maxcolors < 256 else "16"})'
elif Z == 4:
color_mode_str = f' (RGBA:{"8" if maxcolors < 256 else "16"})'
else:
color_mode_str = '' # Just in case
sortir.title(f'{product_name}: {Path(sourcefilename).name}{color_mode_str}{"*" if is_filtered else ""}')
info_normal = {'txt': f'{Path(sourcefilename).name}{"*" if is_filtered else ""} X={X} Y={Y} Z={Z} maxcolors={maxcolors}', 'fg': 'grey', 'bg': 'grey90'}
UINormal()
# ↓ Center window horizontally, +32 vertically
sortir.geometry(f'+{(sortir.winfo_screenwidth() - sortir.winfo_width()) // 2}+32')
def RunFilter(event=None) -> None:
"""Filter image, then preview result."""
global zoom_factor, view_src, is_filtered, is_saved, info_normal, color_mode_str, operation, timing
global preview, preview_filtered
global X, Y, Z, maxcolors, source_image, info
global result_image
method = method_str.get()
UIBusy()
""" ┌─────────────────┐
│ Filtering image │
└─────────────────┘ """
if method == 'Scale2x':
n = 2
sfx = False
elif method == 'Scale3x':
n = 3
sfx = False
elif method == 'Scale2xSFX':
n = 2
sfx = True
elif method == 'Scale3xSFX':
n = 3
sfx = True
if method == 'None':
result_image = source_image
else:
operation = 'Scaling'
start = time()
result_image = scaleNx(source_image, n=n, sfx=sfx)
timing = time() - start
if 'physical' in info:
x_pixels_per_unit, y_pixels_per_unit, unit_is_meter = info['physical']
info['physical'] = [n * x_pixels_per_unit, n * y_pixels_per_unit, unit_is_meter]
Y, X, Z = (len(source_image), len(source_image[0]), len(source_image[0][0]))
YNEW, XNEW = (len(result_image), len(result_image[0]))
# ↓ Flagging as filtered, not saved
if method != 'None':
is_filtered = True
is_saved = False
view_src = False
# ↓ enabling save
menu02.entryconfig('Save', state='normal')
sortir.bind_all('<Control-s>', Save)
# ↓ preview result
preview_data = list2bin(result_image, maxcolors, show_chessboard=True)
preview_filtered = PhotoImage(data=preview_data)
ShowPreview(preview_filtered, 'Result')
# ↓ binding switch on preview click
zanyato.bind('<Button-1>', SwitchView) # left click
zanyato.bind('<space>', SwitchView) # # "Space" key. May be worth binding whole sortir?
# ↓ Center window horizontally, +32 vertically
sortir.geometry(f'+{(sortir.winfo_screenwidth() - sortir.winfo_width()) // 2}+32')
else:
is_filtered = False
is_saved = True
view_src = True
# ↓ disabling save
menu02.entryconfig('Save', state='disabled')
sortir.unbind_all('<Control-s>')
# ↓ binding switch on preview click
zanyato.unbind('<Button-1>') # left click
zanyato.unbind('<space>') # # "Space" key. May be worth binding whole sortir?
# ↓ preview source
ShowPreview(preview_src, 'Source')
# ↓ Adding filename, mode and status to window title a-la Photoshop
sortir.title(f'{product_name}: {Path(sourcefilename).name}{color_mode_str}{"*" if is_filtered else ""}')
info_normal = {'txt': f'{Path(sourcefilename).name}{"*" if is_filtered else ""} X={XNEW if is_filtered else X} Y={YNEW if is_filtered else Y} Z={Z} maxcolors={maxcolors}', 'fg': 'grey', 'bg': 'grey90'}
UINormal()
zanyato.focus_set() # moving focus to preview
def zoomIn(event=None) -> None:
"""Zoom preview in."""
global zoom_factor, view_src, preview
zoom_factor = min(zoom_factor + 1, 4) # max zoom 5
if view_src:
ShowPreview(preview_src, 'Source')
else:
ShowPreview(preview_filtered, 'Result')
# ↓ reenabling +/- buttons
butt_minus.config(state='normal', cursor='hand2')
if zoom_factor == 4: # max zoom 5
butt_plus.config(state='disabled', cursor='arrow')
else:
butt_plus.config(state='normal', cursor='hand2')
def zoomOut(event=None) -> None:
"""Zoom preview out."""
global zoom_factor, view_src, preview
zoom_factor = max(zoom_factor - 1, -19) # min zoom 1/20
if view_src:
ShowPreview(preview_src, 'Source')
else:
ShowPreview(preview_filtered, 'Result')
# ↓ reenabling +/- buttons
butt_plus.config(state='normal', cursor='hand2')
if zoom_factor == -19: # min zoom 1/20
butt_minus.config(state='disabled', cursor='arrow')
else:
butt_minus.config(state='normal', cursor='hand2')
def zoomOne(event=None) -> None:
"""Zoom 1:1."""
global zoom_factor, view_src, preview
zoom_factor = 0
if view_src:
ShowPreview(preview_src, 'Source')
else:
ShowPreview(preview_filtered, 'Result')
# ↓ reenabling +/- buttons
butt_plus.config(state='normal', cursor='hand2')
butt_minus.config(state='normal', cursor='hand2')
def zoomWheel(event) -> None:
"""zoomIn or zoomOut by mouse wheel."""
if event.delta < 0:
zoomOut()
if event.delta > 0:
zoomIn()
def SwitchView(event=None) -> None:
"""Switch preview between preview_src and preview_filtered."""
global zoom_factor, view_src, preview
view_src = not view_src
if view_src:
ShowPreview(preview_src, 'Source')
else:
ShowPreview(preview_filtered, 'Result')
def onSave() -> None:
"""Reassign images and other objects from new to old upon saving."""
global preview_filtered, preview_src, info_normal
global sourcefilename, X, Y, Z, maxcolors, source_image
global resultfilename, result_image
sourcefilename = resultfilename # Now saved file becomes new source file
source_image = result_image
Y, X, Z = (len(result_image), len(result_image[0]), len(result_image[0][0]))
preview_src = preview_filtered
# ↓ Returning method OptionMenu to 'None'
method_str.set('None')
# ↓ disabling save
menu02.entryconfig('Save', state='disabled')
sortir.unbind_all('<Control-s>')
# ↓ binding switch on preview click
zanyato.unbind('<Button-1>') # left click
zanyato.unbind('<space>') # # "Space" key. May be worth binding whole sortir?
# ↓ preview source
ShowPreview(preview_src, 'Source')
# ↓ Adding filename, mode and status to window title a-la Photoshop
sortir.title(f'{product_name}: {Path(sourcefilename).name}{color_mode_str}{"*" if is_filtered else ""}')
info_normal = {'txt': f'{Path(sourcefilename).name}{"*" if is_filtered else ""} X={X} Y={Y} Z={Z} maxcolors={maxcolors}', 'fg': 'grey', 'bg': 'grey90'}
UINormal()
def Save(event=None) -> None:
"""Once pressed on Save."""
global is_filtered, is_saved, info_normal, color_mode_str, operation, timing
global source_image, preview_src, preview_filtered
operation = 'Saving'
if is_saved: # block repetitive saving
return
if not is_filtered: # block useless source resaving
return
resultfilename = sourcefilename
UIBusy()
start = time()
# ↓ Save format choice
if Path(resultfilename).suffix.lower() == '.png':
info['compression'] = 9 # Explicitly setting compression
list2png(resultfilename, result_image, info) # Writing file
elif Path(resultfilename).suffix.lower() in ('.ppm', '.pgm', '.pnm'):
list2pnm(resultfilename, result_image, maxcolors) # Writing file
timing = time() - start
# ↓ Flagging image as saved, not filtered
is_saved = True # to block future repetitive saving
is_filtered = False
onSave()
UINormal()
def SaveAs(event=None) -> None:
"""Once pressed on Save as..."""
global is_saved, is_filtered, info_normal, color_mode_str, operation, timing
global sourcefilename, resultfilename, source_image, preview_src, preview_filtered
operation = 'Saving'
# ↓ Adjusting "Save as" formats to be displayed
# according to bitdepth and source extension
src_extension = Path(sourcefilename).suffix.lower()
if Z == 1:
if src_extension in ('.pgm', '.pnm'):
format_list = [('Portable grey map', '.pgm'), ('Portable network graphics', '.png')]
proposed_name = Path(sourcefilename).stem + '.pgm'
else:
format_list = [('Portable network graphics', '.png'), ('Portable grey map', '.pgm')]
proposed_name = Path(sourcefilename).stem + '.png'
elif Z == 2:
format_list = [('Portable network graphics', '.png')]
proposed_name = Path(sourcefilename).stem + '.png'
elif Z == 3:
if src_extension in ('.ppm', '.pnm'):
format_list = [('Portable pixel map', '.ppm'), ('Portable network graphics', '.png')]
proposed_name = Path(sourcefilename).stem + '.ppm'
else:
format_list = [('Portable network graphics', '.png'), ('Portable pixel map', '.ppm')]
proposed_name = Path(sourcefilename).stem + '.png'
else:
format_list = [('Portable network graphics', '.png')]
proposed_name = Path(sourcefilename).stem + '.png'
# ↓ Open export file
resultfilename = asksaveasfilename(
title='Save image file',
filetypes=format_list,
defaultextension='.png', # No extension should never happen but just in case
initialdir=Path(sourcefilename).parent,
initialfile=proposed_name,
)
if resultfilename == '':
return None
UIBusy()
start = time()
# ↓ Save format choice
if Path(resultfilename).suffix.lower() == '.png':
info['compression'] = 9 # Explicitly setting compression
list2png(resultfilename, result_image, info) # Writing file
elif Path(resultfilename).suffix.lower() in ('.ppm', '.pgm'):
list2pnm(resultfilename, result_image, maxcolors) # Writing file
else:
raise ValueError('Extension not recognized')
timing = time() - start
# ↓ Flagging image as saved, not filtered, and disabling "Save"
is_saved = True # to block future repetitive saving
is_filtered = False
onSave()
UINormal()
""" ╔═══════════╗
║ Main body ║
╚═══════════╝ """
# ↓ Initializing
sourcefilename = ''
zoom_factor = 0
view_src = True
is_filtered = False
product_name = 'Visual ScaleNx'
operation = 'Awaiting orders'
timing = 0
sortir = Tk()
icon_path = Path(__file__).resolve().parent / '32.ico'
if icon_path.exists():
sortir.iconbitmap(icon_path)
else:
sortir.iconphoto(True, PhotoImage(data='P6\n3 3\n255\n'.encode(encoding='ascii') + randbytes(3 * 3 * 3)))
sortir.title(product_name)
# ↓ Info statuses dictionaries
info_normal = {'txt': f'{product_name} {__version__}', 'fg': 'grey', 'bg': 'grey90'}
info_busy = {'txt': 'BUSY, PLEASE WAIT', 'fg': 'red', 'bg': 'yellow'}
color_mode_str = ' '
# ↓ Info string
info_string = Label(sortir, text=info_normal['txt'], font=('courier', 7), foreground=info_normal['fg'], background=info_normal['bg'], relief='groove')
info_string.pack(side='bottom', padx=0, pady=(2, 0), fill='both')
frame_top = Frame(sortir, borderwidth=2, relief='groove')
frame_top.pack(side='top', anchor='nw', pady=2)
frame_preview = Frame(sortir, borderwidth=2, relief='groove')
frame_preview.pack(side='top', anchor='center', expand=True)
""" ┌──────────────────────┐
│ Top frame (controls) │
└─────────────────────-┘ """
# ↓ File menu
butt_file = Menubutton(
frame_top,
text='File...',
width=8,
anchor='w',
font=('helvetica', 12),
cursor='hand2',
relief='groove',
activeforeground='dark blue',
activebackground='#E5F1FB',
border=2,
state='normal',
indicatoron=False,
)
butt_file.pack(side='left', fill='y', padx=(0, 6))
menu02 = Menu(butt_file, tearoff=False) # "File" menu
menu02.add_command(label='Open...', state='normal', command=GetSource, accelerator='Ctrl+O')
menu02.add_separator()
menu02.add_command(label='Save', state='disabled', command=Save, accelerator='Ctrl+S')
menu02.add_command(label='Save as...', state='disabled', command=SaveAs, accelerator='Ctrl+Shift+S')
menu02.add_separator()
menu02.add_command(label='Image Info...', accelerator='Ctrl+I', state='disabled', command=ShowInfo)
menu02.add_separator()
menu02.add_command(label='Exit', state='normal', command=DisMiss, accelerator='Ctrl+Q')
butt_file['menu'] = menu02
# ↓ Filter section begins
info00 = Label(frame_top, text='Scaling method:', font=('helvetica', 12, 'italic'), foreground='brown', state='disabled')
info00.pack(side='left', fill='both', padx=6)
method_str = StringVar(value='None')
method_menu = OptionMenu(
frame_top,
method_str,
*[
'None',
'Scale2x',
'Scale3x',
'Scale2xSFX',
'Scale3xSFX',
],
)
method_menu.pack(side='left')
method_menu.configure(font=('courier', 12), width=10, relief='groove', activebackground='#E5F1FB', state='disabled')
method_menu['menu'].configure(font=method_menu['font'])
method_str.trace_add('write', lambda *args: RunFilter())
""" ┌──────────────────────────────┐
│ Center frame (image preview) │
└─────────────────────────────-┘ """
zanyato = Label(
frame_preview,
text='Preview area.\n Double click to open image,\n Right click or Alt+F for a menu.\nWith image opened,\n Ctrl+Click to zoom in,\n Alt+Click to zoom out,\nWhen filtered, click or Space bar\nto switch source/result.',
font=('helvetica', 12),
justify='left',
borderwidth=2,
padx=12,
pady=12,
background='grey90',
relief='groove',
)
zanyato.pack(side='top')
frame_zoom = Frame(frame_preview, borderwidth=2, relief='groove')
frame_zoom.pack(side='bottom')
butt_plus = Button(frame_zoom, text='+', font=('courier', 8), width=2, cursor='arrow', state='disabled', borderwidth=1, command=zoomIn)
butt_plus.pack(side='left', padx=0, pady=0, fill='both')
butt_minus = Button(frame_zoom, text='-', font=('courier', 8), width=2, cursor='arrow', state='disabled', borderwidth=1, command=zoomOut)
butt_minus.pack(side='right', padx=0, pady=0, fill='both')
label_zoom = Label(frame_zoom, text='Zoom 1:1', font=('courier', 8), state='disabled')
label_zoom.pack(side='left', anchor='n', padx=2, pady=0, fill='both')
""" ┌─────────────────────────────────────────────┐
│ Binding everything that does not need image │
└────────────────────────────────────────────-┘ """
# ↓ Info string binding for displaying scaler execution time
info_string.bind('<Enter>', lambda event=None: info_string.config(text=f'{operation} time: {round(timing, 3)} sec'))
info_string.bind('<Leave>', lambda event=None: info_string.config(text=info_normal['txt']))
info_string.bind('<Control-Button-1>', lambda event=None: [sortir.clipboard_clear(), sortir.clipboard_append(f'{timing}\n')])
# ↓ Double-click image area to "Open..."
zanyato.bind('<Double-Button-1>', GetSource)
frame_preview.bind('<Double-Button-1>', GetSource)
# ↓ Whole sortir binding menu, "Open..." and "Exit"
sortir.bind_all('<Button-3>', ShowMenu)
sortir.bind_all('<Alt-f>', ShowMenu)
sortir.bind_all('<Control-o>', GetSource)
sortir.bind_all('<Control-q>', DisMiss)
# ↓ Center window horizontally, +32 vertically
sortir.update()
# print(sortir.winfo_width(), sortir.winfo_height())
sortir.minsize(frame_top.winfo_width(), sortir.winfo_height())
sortir.maxsize(9 * sortir.winfo_screenwidth() // 10, 9 * sortir.winfo_screenheight() // 10)
sortir.geometry(f'+{(sortir.winfo_screenwidth() - sortir.winfo_width()) // 2}+32')
sortir.mainloop()