2019년 2월 26일 화요일

[Python] wxPython simple wrapper examples


1. wxPython Wrapper


Screenshot:



Application Source: pywx_app.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
import os
import sys
import time
import pywx as ezwx

######################################################################
# Handler
######################################################################

def AppendToText(text):
    ctrl = ezwx.getWxCtrl('text')
    if ctrl is not None:
        ctrl.write( text + "\n" )
        
def onExit(event):
    ezwx.WxAppClose()
    
def onClose(event): #return True if want to exit
    rv = ezwx.MessageYesNo("Alert", "Do you want to quit ?" )
    return rv
        
idle_time = 0
idle_count = 0
def onIdle(event):
    global idle_time
    global idle_count
    curr_time = int(time.time())
    idle_count += 1
    if idle_time != curr_time:
        print(idle_time, idle_count)
        idle_time = curr_time
        idle_count = 0

def onTimer(event):
    AppendToText('[Timer] ' + time.ctime())
    
def onThreadAction():
    AppendToText('[Thread] ' + time.ctime())

def onThread():
    from time import sleep
    while ezwx.isWxAppRun():
        ezwx.callAfter(onThreadAction)
        sleep(1.0)    
        
def onAbout(event):
    ezwx.MessageBox("About", "eezWxPython Demo\nzdiv")
    
def onCopy(event):
    print("onCopy()")
    
def onBrowse(event):
    folder = ezwx.DirectoryDialog()
    text = ezwx.getWxCtrl('folder')
    if text is not None:
        text.Clear()
        text.write(folder)    
    
def onFileBrowse(event):
    files = ezwx.OpenFileDialog()
    if type(files) is list:
        for file in files:
            AppendToText(file)    
    else:
        AppendToText(files) 

def onCalendarButton(event):
    ctrl = ezwx.getWxCtrl('calendar') 
    date = ctrl.GetDate()
    AppendToText(date.Format('%Y-%m-%d')) 

def onDateButton(event):
    ctrl = ezwx.getWxCtrl('date') 
    date = ctrl.GetValue()
    AppendToText(date.Format('%Y-%m-%d')) 

def onTimeButton(event):
    ctrl = ezwx.getWxCtrl('time') 
    h, m, s = ctrl.GetTime()
    AppendToText('%04d:%02d:%02d' % (h,m,s)) 

def onThreadButton(event):
    ezwx.threadHandle(onThread, key='thread')    
    ezwx.threadStart('thread')
        
def onTimerButton(event):
    timer = ezwx.getWxTimer('timer')
    button = ezwx.getWxCtrl('button')
    if button.GetLabel() == 'StartTimer':
        button.SetLabel('StopTimer')
        timer.Start(1000)
    else:
        button.SetLabel('StartTimer')
        timer.Stop()
      
def onChoice(event):
    ctrl = ezwx.getWxCtrl('choice')
    AppendToText(str(ctrl.GetSelection()) + " " + ctrl.GetStringSelection())
        
def onCombo(event):
    ctrl = ezwx.getWxCtrl('combo')
    AppendToText(str(ctrl.GetSelection()) + " " + ctrl.GetStringSelection())
        
def onList(event):
    ctrl = ezwx.getWxCtrl('list')
    AppendToText(str(ctrl.GetSelection()) + " " + ctrl.GetStringSelection())
        
def onCheckList(event):
    ctrl = ezwx.getWxCtrl('checklist')
    AppendToText(str(ctrl.GetSelection()) + " " + ctrl.GetStringSelection())
    
def onCheck(event):
    ctrl = ezwx.getWxCtrl('check1') 
    value = ctrl.GetValue()
    print( 'Check1: ' + str(value))
 
def onRadio(event):
    ctrl = ezwx.getWxCtrl('radio') 
    print( 'Radio: ' + ctrl.GetString(ctrl.GetSelection()))
    
######################################################################
# Popup
######################################################################

popup_body_def = [
    [ ezwx.Bitmap(filename="D:\\Lenna.png",expand=True,proportion=1,key="bitmap"),      
      1 ],
]

popup_layout = {
    "body"   : popup_body_def, 
}

def onImageViewButton(event):
    window = ezwx.WxPopup(u"ezwxApp", 600, 480)
    window.makeLayout(popup_layout)
    window.Show()

######################################################################
# Layout
######################################################################
        
exit_png='eJwBZgWZ+olQTkcNChoKAAAADUlIRFIAAAAgAAAAIAgGAAAAc3p69AAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAUISURBVHjavFfdaxxVFP/de/cj28221hpBTIlNX6qQ9EUNQg1RKKYsfRBfFIL2oeC70AdBfPBJqIr/QLHEKMWH+hFrsxQCarVfVNFEDNU0pGlTTGJTapO4M3Pv9Zw7dze7ss3OImaTk8nOzL3nN7/zOx8DbO5HTF/4srg690P0wZF+S98zqc1yfKn04a5HdnZ+KmF6RSoNJSSfz8tNcK7mfyp9sru7a3pt6bfeubPHYKIIQgi+lm7GQOqjNwY/y2VkUdICkdCjsRZBEKC7Zx+6HnsK4eot3Jj4DtHqMkDXjDVQKn72ZgBy2ZQovnVqjYJFABIiMMZi5e8Alw/tw7Wfx3F3aRZCkisya0JYTQzIZADaRIwCbXRnKwCsTeP69yNYKxtax27IIT05/cIQAOU3awZACCvA9DNgmRAAB0spBUuLjOCQwFEPG4dH67CiASTIAgtJ8WoFAH/4fnZGzxwDAHz86XwUuj0TARBGgu+V0iYHQPcRAUQ3h8K6h68AsJ6BSggapWHm4Huwzx3FSQYoNYdAEWWyZdMEwGjrNFFnTUSY1ySU/l14/q83sSLKyqFVxEBSEXKsJdFlbQMG6EeHodPVvRhIBxp4oe91PNuLobHCOSibpQUp2lS2YMrlu9OBN81HzgIqRKqGgXTxHSyGGtvcRUK7VqYjchjsfREldQK/L38D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oXkjOfnxQu61x6Wzjl96Xh6vPIRXZLaXfZ+dGr/S3jF94+FcWiNUCxs8u33zpNjDyzPhrmYaTccuhafd79SMNQe+TZQeGsicbq6Jll4HXzx6pXnn+fCbzSmtw3+4WpCRaUfqq6l2y6Kn6pZShfJU+NTzDasPdI7ZYlS6lr763IE8tTg5dGo3UHlFr9UpSV3vGOnepw575Y5BZ81X9pGp15EfgOFhsyywOjZVCn9cIU5H4F1PDB791OITrtRVZopw6VzcmBpxV52+MButWVOjxmrmaydWss+twZ+WEqv3rewsnih/5ZtyycGd+yOLMKPMnRwF0S82LvSNNpucO/PngW5irY3pptGV+Gf7j7TnEYntDVQQUq4Hbxp13z7zPbMv9Zd0uL/kOERz+C2G1BH0="

menu_def = { 
    "File" : { 
        "Option" : { 
            "Settings" : None,        # Disabled menu item
            "Copy": onCopy 
        }, 
        "-" : None,                   # Menu separator
        "Exit" : [onExit, exit_png],  # Menu item with base64-encoded icon image
        "-2" : None,                  # Menu separator (should have different name from other menu separator) 
    }, 
    "Help" : { 
        "About" : onAbout 
    },
}

tool_def = [ #icon, text, handler
    [exit_png, onExit, "Exit" ],
    [None],                         # Tool separator
    [save_png, None, "Save", ],     # Disabled toolbar item
]

status_def = [
    ["Ready", -6],   # width will have space with proportion 6 
    ["Status", -4],  # width will have space with proportion 4
    ["Code:1", 20]   # fixed width
]

body_def = [
    [ ezwx.Label ("Folder: "), 
      ezwx.Text  ("Default Text",key="folder",expand=True,proportion=1), 
      ezwx.Button("Folder", handler=onBrowse, key="browse"),
      ezwx.Button("Files", handler=onFileBrowse, key="file_browse" ), ],
    [ ezwx.Check("Check1", handler=onCheck, key='check1'),
      ezwx.Check("Check2", key='check2'), ],
    [ ezwx.Label ("Choices: "), ezwx.Choice(['apple','orange','grape'],0,handler=onChoice,key="choice"),
      ezwx.Label ("  ComboBox: "), ezwx.Combo (['apple','orange','grape'],"orange",handler=onCombo,key="combo"),
      ezwx.Label ("  Date: "), ezwx.Date  (key='date'),
      ezwx.Label ("  Time: "), ezwx.Time  (key='time'), ],
    [ ezwx.List  (['apple','orange','grape'],2,expand=True,proportion=0,handler=onList,key="list"),
      ezwx.List  (['apple','orange','grape'],2,expand=True,proportion=0,handler=onCheckList,check=True,key="checklist"),
      ezwx.Scroll( [
          [ezwx.Radio("Group",["Item1","item2","item3"],"item2",handler=onRadio,key='radio')],
          [ezwx.Button("1")],[ezwx.Button("2")],[ezwx.Button("3")],[ezwx.Button("4")],
          [ezwx.Button("5")],[ezwx.Button("6")],[ezwx.Button("7")],[ezwx.Button("8")],
          [ezwx.Button("9")],[ezwx.Button("10")],
      ], expand=True, proportion=1),
      ezwx.Notebook([
          [
              "StyledText",
              [ ezwx.StyledText ("Default\nMulti Line\nText",expand=True,proportion=1,key="stc"),
                { 'expand' : True, 'proportion' : 1 } ],
          ],      
          [
              "Text",
              [ ezwx.Text  ("Default\nMulti Line\nText",expand=True,proportion=1,multiline=True,key="text"), 
                { 'expand' : True, 'proportion' : 1 } ],
          ],
      ], expand=True, proportion=2, choice=False),  #Stretch Proportion is set to 1
      { 'proportion' : 1 }
    ],
    [ ezwx.Panel([
        [ ezwx.Button("A"), ezwx.Button("B")], 
        [ ezwx.Text("C", expand=True, proportion=1)]
      ]),
      ezwx.Spliter([
          200, #sashpos
          [ 
              [ ezwx.Bitmap(filename="D:\\Lenna.png",expand=True,proportion=1,key="bitmap")],
          ], #panel1
          [
              [ ezwx.Calendar(key='calendar',expand=True,proportion=1)],
          ],  #panel2
      ], expand=True, proportion=1),
      { 'proportion' : 1 }
    ],
    [ None,    #Insert Spacer with proportion 1 
      ezwx.Button("ImageView", handler=onImageViewButton),
      ezwx.Button("Calendar", handler=onCalendarButton),
      ezwx.Button("Date", handler=onDateButton),
      ezwx.Button("Time", handler=onTimeButton),
      ezwx.Button("StartThread", handler=onThreadButton),
      ezwx.Button("StartTimer", handler=onTimerButton, key="button") ],
]

layout = {
    "menu"   : menu_def, 
    "tool"   : tool_def, 
    "status" : status_def, 
    "body"   : body_def, 
}

######################################################################
# Main
######################################################################

def threadTarget():
    ezwx.runAfter(onThread)

if __name__ == "__main__":
    window = ezwx.WxApp(u"ezwxApp", 600, 480)
    window.makeLayout(layout)
    window.closeHandle(onClose)
    window.idleHandle(onIdle)
    window.timerHandle(onTimer, key='timer')
    window.run()


Library Source: pywx.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
import os
import sys
import wx
import wx.stc
import wx.adv
import wx.xrc

from threading import Thread

######################################################################
# Library
######################################################################

ID_START = 1000
CtrlTable = {}
wxAppRun = True
wxAppCloseHandler = None

def getId():
    global ID_START
    ID_START += 1
    return ID_START

def registerCtrl(name,ctrl):
    global CtrlTable
    CtrlTable[name] = ctrl

def getCtrl(name):
    global CtrlTable
    if name in CtrlTable:
        return CtrlTable[name]
    else:
        return None

def getWxCtrl(name):
    global CtrlTable
    if name in CtrlTable:
        return CtrlTable[name].ctrl
    else:
        return None
    
def getWxTimer(name):
    return getCtrl(name)
    
def getWxAppCtrl():
    global CtrlTable
    name = 'WxApp'
    if name in CtrlTable:
        return CtrlTable[name].ctrl
    else:
        return None
    
def encodeIcon(filename):
    from zlib import compress
    from base64 import b64encode
    with open(filename, "rb") as f:
        data = b64encode(compress(f.read()))
    return data
    
def decodeIcon(data):
    from base64 import b64decode
    from zlib import decompress
    image_data = decompress(b64decode(data))
    return image_data

def getBitmap(data):
    from io import BytesIO
    image_data = decodeIcon(data)
    stream = BytesIO(bytearray(image_data)) # just bytes() for py3
    image = wx.Image(stream, wx.BITMAP_TYPE_ANY) # wx.ImageFromStream for legacy wx
    bitmap = wx.Bitmap(image) # wx.BitmapFromImage for legacy wx
    return bitmap
    
def threadHandle(handler,start=False,key=None):
    #from threading import *        
    import threading
    thread = threading.Thread(target=handler)
    if key is not None:
        registerCtrl(key,thread)        
    if start is True:
        thread.start()
        
def threadStart(key):
    thread = getCtrl(key)
    if thread is not None:
        thread.start()
        
def threadJoin(key):
    thread = getCtrl(key)
    if thread is not None:
        thread.join()
  
def callAfter(handler):
    wx.CallAfter(handler)
   
def isWxAppRun():
    global wxAppRun    
    return wxAppRun
       
######################################################################
# Layouts
######################################################################
 
class VBox():
    def __init__(self,orient=wx.VERTICAL,proportion=0):
        self.ctrl = wx.BoxSizer( orient )
    
    def add(self,child,proportion=0,expand=True,border=0,align=0):
        flags = align
        flags |= wx.EXPAND if expand == True else 0
        flags |= wx.ALL if border > 0 else 0            
        self.ctrl.Add( child, proportion, flags, border ) 
        
    def addSpacer(self,proportion=1):
        self.ctrl.Add( ( 0, 0), proportion, wx.EXPAND|wx.ALL, 5 )
    
class HBox(VBox):
    def __init__(self,orient=wx.HORIZONTAL,proportion=0):
        super().__init__(orient,proportion)
        pass

class Control():
    def __init__(self,key=None,expand=False,proportion=0,size=wx.DefaultSize,pos=wx.DefaultPosition,border=2):
        self.ctrl = None
        self.key = key
        self.expand = expand
        self.proportion = proportion    
        self.size = size    
        self.pos = pos    
        self.border=2

######################################################################
# Containers
######################################################################

def wrapSizer(widget):
    sizer = wx.BoxSizer()
    sizer.Add( widget, 1, wx.EXPAND, 0 )
    sizer.Fit( widget )
    return sizer

def dictValue(new_value,old_value):
    try:
        if new_value is not None:
            return new_value
    except:
        pass
    return old_value
    
def makeLayout(layout,parent):
    vbox = VBox()
    for row in layout:
        hbox = HBox()
        prop = 0
        expand = True
        for col in row:
            if type(col) is dict:
                prop = dictValue( col.get('proportion'), prop )
                expand = dictValue( col.get('expand'), expand )
                print( expand )
            elif col is None:
                hbox.addSpacer(proportion=1)
            else:
                col.create(parent)
                hbox.add(col.ctrl,proportion=col.proportion,expand=col.expand,border=col.border,align=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
        vbox.add(hbox.ctrl,proportion=prop,expand=expand,border=2,align=wx.ALIGN_LEFT|wx.ALL)
    return vbox

class Panel(Control):
    def __init__(self,layout,parent=None,create=False,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.layout = layout
        if create is True and parent is not None:
            self.create(parent)
    def create(self,parent):
        self.ctrl = wx.Panel( parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
        self.sizer = makeLayout(self.layout,self.ctrl)
        self.ctrl.SetSizer( self.sizer.ctrl )
        self.ctrl.Layout()      

class Scroll(Control): #TODO
    def __init__(self,layout,parent=None,create=False,horizontal=True,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.layout = layout 
        if create is True and parent is not None:
            self.create(parent)
    def create(self,parent):
        self.ctrl = wx.ScrolledWindow( parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,  wx.HSCROLL|wx.VSCROLL  )
        #self.ctrl.EnableScrolling(True,True)        
        #self.ctrl.SetAutoLayout(1) 
        #self.ctrl.ShowScrollbars( True, True )
        self.sizer = makeLayout(self.layout,self.ctrl)
        self.ctrl.SetSizer( self.sizer.ctrl )
        width = self.ctrl.GetBestSize().width
        height = self.ctrl.GetBestSize().height
        self.ctrl.SetSize((width, height))
        self.ctrl.SetScrollbars( 1, 1, 1, 1 )     
        #self.ctrl.SetScrollRate( 5, 5 )
        #panel = Panel(self.layout, self.ctrl, create=True)
        #self.ctrl.SetSizer( wrapSizer(panel.ctrl) )
        self.ctrl.Layout()   
            
class Spliter(Control):
    def __init__(self,layouts,parent=None,create=False,horizontal=True,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.layouts = layouts #left(top),right(bottom)
        if create is True and parent is not None:
            self.create(parent)
    def create(self,parent):
        self.ctrl = wx.SplitterWindow( parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.SP_3D )
        self.ctrl.Bind( wx.EVT_IDLE, self.onIdle )
        self.sashpos = 0
        self.panels = []
        for layout in self.layouts:
            if type(layout) is int:
                self.sashpos = layout
            else:
                self.panels.append(Panel(layout, self.ctrl, create=True))
        self.ctrl.SplitVertically( self.panels[0].ctrl, self.panels[1].ctrl, self.sashpos )
    def onIdle(self, event):
        self.ctrl.SetSashPosition(self.sashpos)
        self.ctrl.Unbind( wx.EVT_IDLE )    

class Notebook(Control): #TODO
    def __init__(self,layouts,parent=None,create=False,horizontal=True,expand=False,proportion=0,choice=False,key=None):
        super().__init__(key,expand,proportion)
        self.layouts = layouts 
        self.choice = choice
        if create is True and parent is not None:
            self.create(parent)
    def create(self,parent):
        if self.choice is True:
            self.ctrl = wx.Choicebook( parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 )
        else:
            self.ctrl = wx.Notebook( parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 )
        self.panels = []
        for layout in self.layouts:
            title = layout[0]
            layout.remove(title)
            panel = Panel(layout, self.ctrl, create=True)
            self.ctrl.AddPage( panel.ctrl, title, False )

######################################################################
# Controls
######################################################################

class FileDrop(wx.FileDropTarget):
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window
    def OnDropFiles(self, x, y, filenames):
        self.window.drop_handle(filenames)
        return True
    
class Bitmap(Control):
    def __init__(self,filename=None,bitmap=None,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.bitmap = bitmap
        self.filename = filename
    def create(self,parent):
        flags = wx.ALIGN_CENTER
        if self.filename is not None:
            self.bitmap = wx.Bitmap( self.filename, wx.BITMAP_TYPE_ANY )
        self.ctrl = wx.StaticBitmap( parent, wx.ID_ANY, self.bitmap, wx.DefaultPosition, wx.DefaultSize, 0|flags )
        self.ctrl.Bind( wx.EVT_SIZE, self.onEvtBitmapSize )
        if self.key is not None:
            registerCtrl( self.key, self )
    def onEvtBitmapSize(self,event):
        #print("onEvtBitmapSize()",event.GetSize()) #(width, height)
        event.Skip()

class Button(Control):
    def __init__(self,label="",handler=None,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.label = label
        self.handler = handler
    def create(self,parent):        
        id = getId()
        self.ctrl = wx.Button( parent, id, self.label, wx.DefaultPosition, wx.DefaultSize, 0 )
        self.ctrl.Bind( wx.EVT_BUTTON, self.handler, id=id )
        if self.key is not None:
            registerCtrl( self.key, self )

class Calendar(Control):
    def __init__(self,date=None,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.date = date
    def create(self,parent):  
        self.ctrl = wx.adv.CalendarCtrl( parent, wx.ID_ANY, wx.DefaultDateTime, wx.DefaultPosition, wx.DefaultSize, wx.adv.TP_DEFAULT )
        if self.key is not None:
            registerCtrl( self.key, self )
        
class Check(Control):
    def __init__(self,label="",handler=None,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.label = label
        self.handler = handler
    def create(self,parent):        
        id = getId()
        self.ctrl = wx.CheckBox( parent, id, self.label, wx.DefaultPosition, wx.DefaultSize, 0 )
        self.ctrl.Bind( wx.EVT_CHECKBOX, self.handler, id=id )
        if self.key is not None:
            registerCtrl( self.key, self )
                  
class Choice(Control):
    def __init__(self,choices=[],select=0,handler=None,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.choices = choices
        self.select = select
        self.handler = handler
    def create(self,parent):        
        id = getId()
        self.ctrl = wx.Choice( parent, id, wx.DefaultPosition,  wx.DefaultSize, self.choices, 0 )
        self.ctrl.SetSelection(self.select)
        self.ctrl.Bind( wx.EVT_CHOICE, self.handler, id=id )
        if self.key is not None:
            registerCtrl( self.key, self )

class Combo(Control):
    def __init__(self,choices=[],value="",handler=None,expand=False,proportion=0, key=None):
        super().__init__(key,expand,proportion)
        self.choices = choices
        self.value = value
        self.handler = handler
    def create(self,parent):        
        id = getId()
        self.ctrl = wx.ComboBox( parent, id, self.value, wx.DefaultPosition, wx.DefaultSize, self.choices, 0 )
        self.ctrl.Bind( wx.EVT_COMBOBOX, self.handler, id=id )
        if self.key is not None:
            registerCtrl( self.key, self )
     
class Date(Control):
    def __init__(self,date=None,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.date = date
    def create(self,parent):  
        self.ctrl = wx.adv.DatePickerCtrl( parent, wx.ID_ANY, wx.DefaultDateTime, wx.DefaultPosition, wx.DefaultSize, wx.adv.TP_DEFAULT )
        if self.key is not None:
            registerCtrl( self.key, self )
            
class Label(Control):
    def __init__(self,text="",expand=False,proportion=0,multiline=False,key=None):
        super().__init__(key,proportion)
        self.text = text
        self.multiline = multiline
    def create(self,parent):
        flags = 0
        if self.multiline == True:
            flags |= wx.TE_MULTILINE
        self.ctrl = wx.StaticText( parent, wx.ID_ANY, self.text, wx.DefaultPosition, wx.DefaultSize, 0|flags )
        if self.key is not None:
            registerCtrl( self.key, self )
    
class List(Control):
    def __init__(self,choices=[],select=0,handler=None,expand=False,proportion=0,check=False,key=None):
        super().__init__(key,expand,proportion)
        self.choices = choices
        self.select = select
        self.handler = handler
        self.check = check
    def create(self,parent):        
        id = getId()
        if self.check is True:
            self.ctrl = wx.CheckListBox( parent, id, wx.DefaultPosition,  wx.DefaultSize, self.choices, 0 )
        else:
            self.ctrl = wx.ListBox( parent, id, wx.DefaultPosition,  wx.DefaultSize, self.choices, 0 )
        self.ctrl.SetSelection(self.select)
        self.ctrl.Bind( wx.EVT_LISTBOX, self.handler, id=id )
        if self.key is not None:
            registerCtrl( self.key, self )

class Radio(Control):
    def __init__(self,label="",choices=[],value="",handler=None,expand=False,proportion=0,style='row',key=None):
        super().__init__(key,expand,proportion)
        self.label = label
        self.choices = choices
        self.value = value
        self.handler = handler
        self.style = wx.RA_SPECIFY_ROWS if style == 'row' else wx.RA_SPECIFY_COLS
    def create(self,parent):        
        id = getId()
        self.ctrl = wx.RadioBox( parent, id, self.label, wx.DefaultPosition, wx.DefaultSize, self.choices, 0, self.style )
        self.ctrl.Bind( wx.EVT_RADIOBOX, self.handler, id=id )
        for i in range(len(self.choices)):
            if self.value == self.choices[i]:
                self.ctrl.SetSelection(i)
                break
        if self.key is not None:
            registerCtrl( self.key, self )
            
class StyledText(Control):
    def __init__(self,text="",expand=True,proportion=1,key=None):
        super().__init__(key,expand,proportion)
        self.text = text
    def create(self,parent):
        flags = 0
        self.ctrl = wx.stc.StyledTextCtrl( parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0|flags )
        self.enableLineNumber()
        self.ctrl.SetText(self.text)
        drop_target = FileDrop(self)
        self.ctrl.SetDropTarget(drop_target)
        if self.key is not None:
            registerCtrl( self.key, self )
    def drop_handle(self,filenames):
        for filename in filenames:
            self.ctrl.AppendText( filename + '\n' )
            if self.multiline is False:
                break
    def enableLineNumber(self):
        #self.stc.SetProperty("fold", "1")
        #self.stc.SetProperty("fold.html", "1")
        self.ctrl.SetMargins(0, 0)
        self.ctrl.SetMarginType(1, wx.stc.STC_MARGIN_NUMBER)
        self.ctrl.SetMarginMask(2, wx.stc.STC_MASK_FOLDERS)
        self.ctrl.SetMarginSensitive(2, True)
        self.ctrl.SetMarginWidth(1, 32) # 2,25
        self.ctrl.SetMarginWidth(2, 16) # 2,25
        
class Text(Control):
    def __init__(self,text="",expand=True,proportion=0,size=wx.DefaultSize,pos=wx.DefaultPosition,
                 multiline=False,password=False,readonly=False,key=None):
        super().__init__(key,expand,proportion,size,pos)
        self.text = text
        self.multiline = multiline
        self.password = password
        self.readonly = readonly
        #self.expand = True if multiline == True else False
    def create(self,parent):
        flags = 0
        flags |= wx.TE_MULTILINE if self.multiline is True else 0
        flags |= wx.TE_PASSWORD if self.password is True else 0
        flags |= wx.TE_READONLY if self.readonly is True else 0
        self.ctrl = wx.TextCtrl( parent, wx.ID_ANY, self.text, self.pos, self.size, 0|flags )
        drop_target = FileDrop(self)
        self.ctrl.SetDropTarget(drop_target)
        if self.key is not None:
            registerCtrl( self.key, self )
    def drop_handle(self,filenames):
        for filename in filenames:
            self.ctrl.AppendText( filename + '\n' )
            if self.multiline is False:
                break
            
class Time(Control):
    def __init__(self,date=None,expand=False,proportion=0,key=None):
        super().__init__(key,expand,proportion)
        self.date = date
    def create(self,parent):  
        self.ctrl = wx.adv.TimePickerCtrl( parent, wx.ID_ANY, wx.DefaultDateTime, wx.DefaultPosition, wx.DefaultSize, wx.adv.TP_DEFAULT )
        if self.key is not None:
            registerCtrl( self.key, self )
            
######################################################################
# Dialogs
######################################################################
            
def OpenFileDialog(defaultDir="",multiple=False,save=False):
    style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST if save is False else wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT
    style |= wx.FD_MULTIPLE if multiple is True else 0
    dlg = wx.FileDialog(None,defaultDir=defaultDir,style=style)
    rv = dlg.ShowModal()
    if rv == wx.ID_OK:
        if multiple == True:
            files = []
            for file in dlg.GetFilenames():
                files.append( os.path.join(dlg.GetDirectory(), file) )
            return files
        else:
            return os.path.join(dlg.GetDirectory(), dlg.GetFilename())
    else:
        return None
    
def SaveFileDialog(defaultDir=""):
    return OpenFileDialog(defaultDir=defaultDir, multiple=False, save=True)

def DirectoryDialog(defaultPath=""):
    dlg = wx.DirDialog(None,defaultPath=defaultPath)
    rv = dlg.ShowModal()
    if rv == wx.ID_OK:
        return dlg.GetPath()
    else:
        return None

def MessageBox(title,message):
    dlg = wx.MessageDialog(None, message, caption=title, style=wx.OK|wx.CENTER, pos=wx.DefaultPosition)    
    dlg.ShowModal()
    
def MessageYesNo(title,message):
    dlg = wx.MessageDialog(None, message, caption=title, style=wx.YES|wx.NO|wx.CENTER, pos=wx.DefaultPosition)     
    rv = dlg.ShowModal()
    if rv == wx.ID_OK or rv == wx.ID_YES:
        return True
    else: #wx.ID_CANCEL, wx.ID_NO 
        return False
    
def MessageYesNoCancel(title,message):
    dlg = wx.MessageDialog(None, message, caption=title, style=wx.YES|wx.NO|wx.CANCEL|wx.CENTER, pos=wx.DefaultPosition)     
    rv = dlg.ShowModal()
    if rv == wx.ID_OK or rv == wx.ID_YES:
        return True
    elif rv == wx.ID_NO:
        return False
    else: #wx.ID_CANCEL, 
        return None
    
######################################################################
# WxApp
######################################################################

WxMainWindow = None

def WxAppClose():
    global WxMainWindow
    WxMainWindow.frame.Close()
    
def WxAppCloseEvent(event):
    global wxAppRun
    global wxAppCloseHandler
    wxAppRun = False
    if wxAppCloseHandler is not None:
        if wxAppCloseHandler(event) == True:
            event.Skip()
    else:
        event.Skip()
            
class WxApp():
    def __init__( self, title, width=800, height=600, popup=False ):
        global WxMainWindow
        if popup is False:
            WxMainWindow = self
            self.app = wx.PySimpleApp()
            self.frame = wx.Frame( parent=None, id = wx.ID_ANY, title = title, pos = wx.DefaultPosition, size = wx.Size( width,height ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
            self.frame.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) 
            self.frame.Bind(wx.EVT_CLOSE, WxAppCloseEvent)
            registerCtrl( 'WxApp', self )
        else:
            self.frame = wx.Frame( parent=None, id = wx.ID_ANY, title = title, pos = wx.DefaultPosition, size = wx.Size( width,height ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
            self.frame.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) 
            
    def run(self):
        self.frame.Show()
        self.app.MainLoop()
    
    def close(self):
        self.frame.Close()
        
    def Show(self):
        self.frame.Show()
        
    def closeHandle(self,handler):
        global wxAppCloseHandler
        wxAppCloseHandler = handler
     
    def idleHandle(self,handler):
        self.frame.Bind(wx.EVT_IDLE, handler)

    def timerHandle(self,handler,interval=1000,start=False,key=None):
        timer = wx.Timer(self.frame)
        self.frame.Bind(wx.EVT_TIMER, handler, timer)
        if key is not None:
            registerCtrl(key,timer)
        if start is True and interval > 0:
            timer.Start(interval)
            
    def timerStart(key,interval):
        timer = getWxTimer(key)
        if timer is not None and interval > 0:
            timer.Start(interval)
        
    def timerStop(key):
        timer = getWxTimer(key)
        if timer is not None:
            timer.Stop()
            
    def makeMenu(self, value):
        menu = wx.Menu()
        for k, v in value.items():
            if k[0] == '-':
                menu.AppendSeparator()
            else:
                if type(v) is dict:
                    submenu = self.makeMenu(v)
                    menu.AppendSubMenu(submenu, k)
                else:
                    if type(v) is list:
                        handler = v[0]
                        icon = v[1]
                    else: 
                        handler = v
                        icon = None
                    item = wx.MenuItem( menu, getId(), k, wx.EmptyString, wx.ITEM_NORMAL )
                    if icon is not None:
                        item.SetBitmap(getBitmap(icon))
                    if handler is None:
                        item.Enable( False )
                    else:
                        self.frame.Bind(wx.EVT_MENU, handler, item)
                    menu.Append(item)
        return menu
    
    def makeMenuBar(self, menu_def):
        self.menubar = wx.MenuBar(0)
        for key, value in menu_def.items():
            if type(value) is dict:
                menu = self.makeMenu(value)
                self.menubar.Append( menu, key )
        self.frame.SetMenuBar(self.menubar)
            
    def makeStatusBar(self, status_def):
        self.statusbar = self.frame.CreateStatusBar( len(status_def), wx.STB_SIZEGRIP, wx.ID_ANY )
        widths = []
        for i in range(len(status_def)):
            self.statusbar.SetStatusText( status_def[i][0], i)
            widths.append(status_def[i][1])
        self.statusbar.SetStatusWidths(widths)
            
    def makeToolBar(self, tool_def):  #icon, text, handler
        flags = wx.TB_FLAT|wx.TB_HORIZONTAL
        if len(tool_def[0]) == 3:
            flags |= wx.TB_TEXT
        self.toolbar = self.frame.CreateToolBar( flags, wx.ID_ANY )
        for value in tool_def:
            if value[0] is None:
                self.toolbar.AddSeparator()
            else:
                text = handler = None
                if len(value) >= 2:
                    handler = value[1]
                if len(value) == 3:
                    text = value[2]
                icon = getBitmap(value[0])
                id = getId()
                if flags & wx.TB_TEXT:
                    tool = self.toolbar.AddLabelTool( id, text, icon, wx.NullBitmap, wx.ITEM_NORMAL, wx.EmptyString, wx.EmptyString, None )
                else:
                    tool = self.toolbar.AddSimpleTool( id, icon, wx.EmptyString, wx.EmptyString, None )
                if handler is None:
                    tool.Enable( False )               
                else:    
                    self.toolbar.Bind( wx.EVT_TOOL, handler, id = id )
        self.toolbar.Realize()

    def makeBody(self,body_def):
        '''
        self.sizer = wx.BoxSizer()
        self.panel = Panel(body_def,self.frame,create=True)
        self.sizer.Add( self.panel.ctrl, 1, wx.EXPAND, 0 )
        self.sizer.Fit( self.panel.ctrl )
        self.frame.SetSizer( self.sizer )
        '''
        self.panel = Panel(body_def,self.frame,create=True)
        self.frame.SetSizer( wrapSizer(self.panel.ctrl) )
        self.frame.Layout()          

    def makeLayout(self,layout):
        if 'menu' in layout:
            self.makeMenuBar(layout['menu'])
        if 'tool' in layout:
            self.makeToolBar(layout['tool'])
        if 'status' in layout:
            self.makeStatusBar(layout['status'])
        if 'body' in layout:
            self.makeBody(layout['body'])

class WxPopup(WxApp):
    def __init__( self, title, width=800, height=600 ):
        super().__init__( title, width=width, height=height, popup=True )

댓글 없음:

댓글 쓰기