-
Notifications
You must be signed in to change notification settings - Fork 0
/
easygui.py
2492 lines (1980 loc) · 85.6 KB
/
easygui.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
"""
@version: 0.96(2010-08-29)
@note:
ABOUT EASYGUI
EasyGui provides an easy-to-use interface for simple GUI interaction
with a user. It does not require the programmer to know anything about
tkinter, frames, widgets, callbacks or lambda. All GUI interactions are
invoked by simple function calls that return results.
@note:
WARNING about using EasyGui with IDLE
You may encounter problems using IDLE to run programs that use EasyGui. Try it
and find out. EasyGui is a collection of Tkinter routines that run their own
event loops. IDLE is also a Tkinter application, with its own event loop. The
two may conflict, with unpredictable results. If you find that you have
problems, try running your EasyGui program outside of IDLE.
Note that EasyGui requires Tk release 8.0 or greater.
@note:
LICENSE INFORMATION
EasyGui version 0.96
Copyright (c) 2010, Stephen Raymond Ferg
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@note:
ABOUT THE EASYGUI LICENSE
This license is what is generally known as the "modified BSD license",
aka "revised BSD", "new BSD", "3-clause BSD".
See http://www.opensource.org/licenses/bsd-license.php
This license is GPL-compatible.
See http://en.wikipedia.org/wiki/License_compatibility
See http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses
The BSD License is less restrictive than GPL.
It allows software released under the license to be incorporated into proprietary products.
Works based on the software may be released under a proprietary license or as closed source software.
http://en.wikipedia.org/wiki/BSD_licenses#3-clause_license_.28.22New_BSD_License.22.29
"""
egversion = __doc__.split()[1]
__all__ = ['ynbox'
, 'ccbox'
, 'boolbox'
, 'indexbox'
, 'msgbox'
, 'buttonbox'
, 'integerbox'
, 'multenterbox'
, 'enterbox'
, 'exceptionbox'
, 'choicebox'
, 'codebox'
, 'textbox'
, 'diropenbox'
, 'fileopenbox'
, 'filesavebox'
, 'passwordbox'
, 'multpasswordbox'
, 'multchoicebox'
, 'abouteasygui'
, 'egversion'
, 'egdemo'
, 'EgStore'
]
import sys, os
import string
import pickle
import traceback
#--------------------------------------------------
# check python version and take appropriate action
#--------------------------------------------------
"""
From the python documentation:
sys.hexversion contains the version number encoded as a single integer. This is
guaranteed to increase with each version, including proper support for non-
production releases. For example, to test that the Python interpreter is at
least version 1.5.2, use:
if sys.hexversion >= 0x010502F0:
# use some advanced feature
...
else:
# use an alternative implementation or warn the user
...
"""
if sys.hexversion >= 0x020600F0:
runningPython26 = True
else:
runningPython26 = False
if sys.hexversion >= 0x030000F0:
runningPython3 = True
else:
runningPython3 = False
try:
from PIL import Image as PILImage
from PIL import ImageTk as PILImageTk
PILisLoaded = True
except:
PILisLoaded = False
if runningPython3:
from tkinter import *
import tkinter.filedialog as tk_FileDialog
from io import StringIO
else:
from Tkinter import *
import tkFileDialog as tk_FileDialog
from StringIO import StringIO
def write(*args):
args = [str(arg) for arg in args]
args = " ".join(args)
sys.stdout.write(args)
def writeln(*args):
write(*args)
sys.stdout.write("\n")
say = writeln
if TkVersion < 8.0 :
stars = "*"*75
writeln("""\n\n\n""" + stars + """
You are running Tk version: """ + str(TkVersion) + """
You must be using Tk version 8.0 or greater to use EasyGui.
Terminating.
""" + stars + """\n\n\n""")
sys.exit(0)
def dq(s):
return '"%s"' % s
rootWindowPosition = "+300+200"
PROPORTIONAL_FONT_FAMILY = ("MS", "Sans", "Serif")
MONOSPACE_FONT_FAMILY = ("Courier")
PROPORTIONAL_FONT_SIZE = 10
MONOSPACE_FONT_SIZE = 9 #a little smaller, because it it more legible at a smaller size
TEXT_ENTRY_FONT_SIZE = 12 # a little larger makes it easier to see
#STANDARD_SELECTION_EVENTS = ["Return", "Button-1"]
STANDARD_SELECTION_EVENTS = ["Return", "Button-1", "space"]
# Initialize some global variables that will be reset later
__choiceboxMultipleSelect = None
__widgetTexts = None
__replyButtonText = None
__choiceboxResults = None
__firstWidget = None
__enterboxText = None
__enterboxDefaultText=""
__multenterboxText = ""
choiceboxChoices = None
choiceboxWidget = None
entryWidget = None
boxRoot = None
ImageErrorMsg = (
"\n\n---------------------------------------------\n"
"Error: %s\n%s")
#-------------------------------------------------------------------
# various boxes built on top of the basic buttonbox
#-----------------------------------------------------------------------
#-----------------------------------------------------------------------
# ynbox
#-----------------------------------------------------------------------
def ynbox(msg="Shall I continue?"
, title=" "
, choices=("Yes", "No")
, image=None
):
"""
Display a msgbox with choices of Yes and No.
The default is "Yes".
The returned value is calculated this way::
if the first choice ("Yes") is chosen, or if the dialog is cancelled:
return 1
else:
return 0
If invoked without a msg argument, displays a generic request for a confirmation
that the user wishes to continue. So it can be used this way::
if ynbox(): pass # continue
else: sys.exit(0) # exit the program
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed
"""
return boolbox(msg, title, choices, image=image)
#-----------------------------------------------------------------------
# ccbox
#-----------------------------------------------------------------------
def ccbox(msg="Shall I continue?"
, title=" "
, choices=("Continue", "Cancel")
, image=None
):
"""
Display a msgbox with choices of Continue and Cancel.
The default is "Continue".
The returned value is calculated this way::
if the first choice ("Continue") is chosen, or if the dialog is cancelled:
return 1
else:
return 0
If invoked without a msg argument, displays a generic request for a confirmation
that the user wishes to continue. So it can be used this way::
if ccbox():
pass # continue
else:
sys.exit(0) # exit the program
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed
"""
return boolbox(msg, title, choices, image=image)
#-----------------------------------------------------------------------
# boolbox
#-----------------------------------------------------------------------
def boolbox(msg="Shall I continue?"
, title=" "
, choices=("Yes","No")
, image=None
):
"""
Display a boolean msgbox.
The default is the first choice.
The returned value is calculated this way::
if the first choice is chosen, or if the dialog is cancelled:
returns 1
else:
returns 0
"""
reply = buttonbox(msg=msg, choices=choices, title=title, image=image)
if reply == choices[0]: return 1
else: return 0
#-----------------------------------------------------------------------
# indexbox
#-----------------------------------------------------------------------
def indexbox(msg="Shall I continue?"
, title=" "
, choices=("Yes","No")
, image=None
):
"""
Display a buttonbox with the specified choices.
Return the index of the choice selected.
"""
reply = buttonbox(msg=msg, choices=choices, title=title, image=image)
index = -1
for choice in choices:
index = index + 1
if reply == choice: return index
raise AssertionError(
"There is a program logic error in the EasyGui code for indexbox.")
#-----------------------------------------------------------------------
# msgbox
#-----------------------------------------------------------------------
def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK",image=None,root=None):
"""
Display a messagebox
"""
if type(ok_button) != type("OK"):
raise AssertionError("The 'ok_button' argument to msgbox must be a string.")
return buttonbox(msg=msg, title=title, choices=[ok_button], image=image,root=root)
#-------------------------------------------------------------------
# buttonbox
#-------------------------------------------------------------------
def buttonbox(msg="",title=" "
,choices=("Button1", "Button2", "Button3")
, image=None
, root=None
):
"""
Display a msg, a title, and a set of buttons.
The buttons are defined by the members of the choices list.
Return the text of the button that the user selected.
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed
"""
global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame
# Initialize __replyButtonText to the first choice.
# This is what will be used if the window is closed by the close button.
__replyButtonText = choices[0]
if root:
root.withdraw()
boxRoot = Toplevel(master=root)
boxRoot.withdraw()
else:
boxRoot = Tk()
boxRoot.withdraw()
boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
boxRoot.title(title)
boxRoot.iconname('Dialog')
boxRoot.geometry(rootWindowPosition)
boxRoot.minsize(400, 100)
# ------------- define the messageFrame ---------------------------------
messageFrame = Frame(master=boxRoot)
messageFrame.pack(side=TOP, fill=BOTH)
# ------------- define the imageFrame ---------------------------------
tk_Image = None
if image:
imageFilename = os.path.normpath(image)
junk,ext = os.path.splitext(imageFilename)
if os.path.exists(imageFilename):
if ext.lower() in [".gif", ".pgm", ".ppm"]:
tk_Image = PhotoImage(master=boxRoot, file=imageFilename)
else:
if PILisLoaded:
try:
pil_Image = PILImage.open(imageFilename)
tk_Image = PILImageTk.PhotoImage(pil_Image, master=boxRoot)
except:
msg += ImageErrorMsg % (imageFilename,
"\nThe Python Imaging Library (PIL) could not convert this file to a displayable image."
"\n\nPIL reports:\n" + exception_format())
else: # PIL is not loaded
msg += ImageErrorMsg % (imageFilename,
"\nI could not import the Python Imaging Library (PIL) to display the image.\n\n"
"You may need to install PIL\n"
"(http://www.pythonware.com/products/pil/)\n"
"to display " + ext + " image files.")
else:
msg += ImageErrorMsg % (imageFilename, "\nImage file not found.")
if tk_Image:
imageFrame = Frame(master=boxRoot)
imageFrame.pack(side=TOP, fill=BOTH)
label = Label(imageFrame,image=tk_Image)
label.image = tk_Image # keep a reference!
label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m')
# ------------- define the buttonsFrame ---------------------------------
buttonsFrame = Frame(master=boxRoot)
buttonsFrame.pack(side=TOP, fill=BOTH)
# -------------------- place the widgets in the frames -----------------------
messageWidget = Message(messageFrame, text=msg, width=400)
messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m')
__put_buttons_in_buttonframe(choices)
# -------------- the action begins -----------
# put the focus on the first button
__firstWidget.focus_force()
boxRoot.deiconify()
boxRoot.mainloop()
boxRoot.destroy()
if root: root.deiconify()
return __replyButtonText
#-------------------------------------------------------------------
# integerbox
#-------------------------------------------------------------------
def integerbox(msg=""
, title=" "
, default=""
, lowerbound=0
, upperbound=99
, image = None
, root = None
, **invalidKeywordArguments
):
"""
Show a box in which a user can enter an integer.
In addition to arguments for msg and title, this function accepts
integer arguments for "default", "lowerbound", and "upperbound".
The default argument may be None.
When the user enters some text, the text is checked to verify that it
can be converted to an integer between the lowerbound and upperbound.
If it can be, the integer (not the text) is returned.
If it cannot, then an error msg is displayed, and the integerbox is
redisplayed.
If the user cancels the operation, None is returned.
NOTE that the "argLowerBound" and "argUpperBound" arguments are no longer
supported. They have been replaced by "upperbound" and "lowerbound".
"""
if "argLowerBound" in invalidKeywordArguments:
raise AssertionError(
"\nintegerbox no longer supports the 'argLowerBound' argument.\n"
+ "Use 'lowerbound' instead.\n\n")
if "argUpperBound" in invalidKeywordArguments:
raise AssertionError(
"\nintegerbox no longer supports the 'argUpperBound' argument.\n"
+ "Use 'upperbound' instead.\n\n")
if default != "":
if type(default) != type(1):
raise AssertionError(
"integerbox received a non-integer value for "
+ "default of " + dq(str(default)) , "Error")
if type(lowerbound) != type(1):
raise AssertionError(
"integerbox received a non-integer value for "
+ "lowerbound of " + dq(str(lowerbound)) , "Error")
if type(upperbound) != type(1):
raise AssertionError(
"integerbox received a non-integer value for "
+ "upperbound of " + dq(str(upperbound)) , "Error")
if msg == "":
msg = ("Enter an integer between " + str(lowerbound)
+ " and "
+ str(upperbound)
)
while 1:
reply = enterbox(msg, title, str(default), image=image, root=root)
if reply == None: return None
try:
reply = int(reply)
except:
msgbox ("The value that you entered:\n\t%s\nis not an integer." % dq(str(reply))
, "Error")
continue
if reply < lowerbound:
msgbox ("The value that you entered is less than the lower bound of "
+ str(lowerbound) + ".", "Error")
continue
if reply > upperbound:
msgbox ("The value that you entered is greater than the upper bound of "
+ str(upperbound) + ".", "Error")
continue
# reply has passed all validation checks.
# It is an integer between the specified bounds.
return reply
#-------------------------------------------------------------------
# multenterbox
#-------------------------------------------------------------------
def multenterbox(msg="Fill in values for the fields."
, title=" "
, fields=()
, values=()
):
r"""
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with
empty strings until the number of values is the same as the number of names.
If there are more values than names, the list of values
is truncated so that there are as many values as names.
Returns a list of the values of the fields,
or None if the user cancels the operation.
Here is some example code, that shows how values returned from
multenterbox can be checked for validity before they are accepted::
----------------------------------------------------------------------
msg = "Enter your personal information"
title = "Credit Card Application"
fieldNames = ["Name","Street Address","City","State","ZipCode"]
fieldValues = [] # we start with blanks for the values
fieldValues = multenterbox(msg,title, fieldNames)
# make sure that none of the fields was left blank
while 1:
if fieldValues == None: break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg += ('"%s" is a required field.\n\n' % fieldNames[i])
if errmsg == "":
break # no problems found
fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues)
writeln("Reply was: %s" % str(fieldValues))
----------------------------------------------------------------------
@arg msg: the msg to be displayed.
@arg title: the window title
@arg fields: a list of fieldnames.
@arg values: a list of field values
"""
return __multfillablebox(msg,title,fields,values,None)
#-----------------------------------------------------------------------
# multpasswordbox
#-----------------------------------------------------------------------
def multpasswordbox(msg="Fill in values for the fields."
, title=" "
, fields=tuple()
,values=tuple()
):
r"""
Same interface as multenterbox. But in multpassword box,
the last of the fields is assumed to be a password, and
is masked with asterisks.
Example
=======
Here is some example code, that shows how values returned from
multpasswordbox can be checked for validity before they are accepted::
msg = "Enter logon information"
title = "Demo of multpasswordbox"
fieldNames = ["Server ID", "User ID", "Password"]
fieldValues = [] # we start with blanks for the values
fieldValues = multpasswordbox(msg,title, fieldNames)
# make sure that none of the fields was left blank
while 1:
if fieldValues == None: break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i])
if errmsg == "": break # no problems found
fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues)
writeln("Reply was: %s" % str(fieldValues))
"""
return __multfillablebox(msg,title,fields,values,"*")
def bindArrows(widget):
widget.bind("<Down>", tabRight)
widget.bind("<Up>" , tabLeft)
widget.bind("<Right>",tabRight)
widget.bind("<Left>" , tabLeft)
def tabRight(event):
boxRoot.event_generate("<Tab>")
def tabLeft(event):
boxRoot.event_generate("<Shift-Tab>")
#-----------------------------------------------------------------------
# __multfillablebox
#-----------------------------------------------------------------------
def __multfillablebox(msg="Fill in values for the fields."
, title=" "
, fields=()
, values=()
, mask = None
):
global boxRoot, __multenterboxText, __multenterboxDefaultText, cancelButton, entryWidget, okButton
choices = ["OK", "Cancel"]
if len(fields) == 0: return None
fields = list(fields[:]) # convert possible tuples to a list
values = list(values[:]) # convert possible tuples to a list
if len(values) == len(fields): pass
elif len(values) > len(fields):
fields = fields[0:len(values)]
else:
while len(values) < len(fields):
values.append("")
boxRoot = Tk()
boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
boxRoot.title(title)
boxRoot.iconname('Dialog')
boxRoot.geometry(rootWindowPosition)
boxRoot.bind("<Escape>", __multenterboxCancel)
# -------------------- put subframes in the boxRoot --------------------
messageFrame = Frame(master=boxRoot)
messageFrame.pack(side=TOP, fill=BOTH)
#-------------------- the msg widget ----------------------------
messageWidget = Message(messageFrame, width="4.5i", text=msg)
messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
messageWidget.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m')
global entryWidgets
entryWidgets = []
lastWidgetIndex = len(fields) - 1
for widgetIndex in range(len(fields)):
argFieldName = fields[widgetIndex]
argFieldValue = values[widgetIndex]
entryFrame = Frame(master=boxRoot)
entryFrame.pack(side=TOP, fill=BOTH)
# --------- entryWidget ----------------------------------------------
labelWidget = Label(entryFrame, text=argFieldName)
labelWidget.pack(side=LEFT)
entryWidget = Entry(entryFrame, width=40,highlightthickness=2)
entryWidgets.append(entryWidget)
entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,TEXT_ENTRY_FONT_SIZE))
entryWidget.pack(side=RIGHT, padx="3m")
bindArrows(entryWidget)
entryWidget.bind("<Return>", __multenterboxGetText)
entryWidget.bind("<Escape>", __multenterboxCancel)
# for the last entryWidget, if this is a multpasswordbox,
# show the contents as just asterisks
if widgetIndex == lastWidgetIndex:
if mask:
entryWidgets[widgetIndex].configure(show=mask)
# put text into the entryWidget
entryWidgets[widgetIndex].insert(0,argFieldValue)
widgetIndex += 1
# ------------------ ok button -------------------------------
buttonsFrame = Frame(master=boxRoot)
buttonsFrame.pack(side=BOTTOM, fill=BOTH)
okButton = Button(buttonsFrame, takefocus=1, text="OK")
bindArrows(okButton)
okButton.pack(expand=1, side=LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m')
# for the commandButton, bind activation events to the activation event handler
commandButton = okButton
handler = __multenterboxGetText
for selectionEvent in STANDARD_SELECTION_EVENTS:
commandButton.bind("<%s>" % selectionEvent, handler)
# ------------------ cancel button -------------------------------
cancelButton = Button(buttonsFrame, takefocus=1, text="Cancel")
bindArrows(cancelButton)
cancelButton.pack(expand=1, side=RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m')
# for the commandButton, bind activation events to the activation event handler
commandButton = cancelButton
handler = __multenterboxCancel
for selectionEvent in STANDARD_SELECTION_EVENTS:
commandButton.bind("<%s>" % selectionEvent, handler)
# ------------------- time for action! -----------------
entryWidgets[0].focus_force() # put the focus on the entryWidget
boxRoot.mainloop() # run it!
# -------- after the run has completed ----------------------------------
boxRoot.destroy() # button_click didn't destroy boxRoot, so we do it now
return __multenterboxText
#-----------------------------------------------------------------------
# __multenterboxGetText
#-----------------------------------------------------------------------
def __multenterboxGetText(event):
global __multenterboxText
__multenterboxText = []
for entryWidget in entryWidgets:
__multenterboxText.append(entryWidget.get())
boxRoot.quit()
def __multenterboxCancel(event):
global __multenterboxText
__multenterboxText = None
boxRoot.quit()
#-------------------------------------------------------------------
# enterbox
#-------------------------------------------------------------------
def enterbox(msg="Enter something."
, title=" "
, default=""
, strip=True
, image=None
, root=None
):
"""
Show a box in which a user can enter some text.
You may optionally specify some default text, which will appear in the
enterbox when it is displayed.
Returns the text that the user entered, or None if he cancels the operation.
By default, enterbox strips its result (i.e. removes leading and trailing
whitespace). (If you want it not to strip, use keyword argument: strip=False.)
This makes it easier to test the results of the call::
reply = enterbox(....)
if reply:
...
else:
...
"""
result = __fillablebox(msg, title, default=default, mask=None,image=image,root=root)
if result and strip:
result = result.strip()
return result
def passwordbox(msg="Enter your password."
, title=" "
, default=""
, image=None
, root=None
):
"""
Show a box in which a user can enter a password.
The text is masked with asterisks, so the password is not displayed.
Returns the text that the user entered, or None if he cancels the operation.
"""
return __fillablebox(msg, title, default, mask="*",image=image,root=root)
def __fillablebox(msg
, title=""
, default=""
, mask=None
, image=None
, root=None
):
"""
Show a box in which a user can enter some text.
You may optionally specify some default text, which will appear in the
enterbox when it is displayed.
Returns the text that the user entered, or None if he cancels the operation.
"""
global boxRoot, __enterboxText, __enterboxDefaultText
global cancelButton, entryWidget, okButton
if title == None: title == ""
if default == None: default = ""
__enterboxDefaultText = default
__enterboxText = __enterboxDefaultText
if root:
root.withdraw()
boxRoot = Toplevel(master=root)
boxRoot.withdraw()
else:
boxRoot = Tk()
boxRoot.withdraw()
boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
boxRoot.title(title)
boxRoot.iconname('Dialog')
boxRoot.geometry(rootWindowPosition)
boxRoot.bind("<Escape>", __enterboxCancel)
# ------------- define the messageFrame ---------------------------------
messageFrame = Frame(master=boxRoot)
messageFrame.pack(side=TOP, fill=BOTH)
# ------------- define the imageFrame ---------------------------------
tk_Image = None
if image:
imageFilename = os.path.normpath(image)
junk,ext = os.path.splitext(imageFilename)
if os.path.exists(imageFilename):
if ext.lower() in [".gif", ".pgm", ".ppm"]:
tk_Image = PhotoImage(master=boxRoot, file=imageFilename)
else:
if PILisLoaded:
try:
pil_Image = PILImage.open(imageFilename)
tk_Image = PILImageTk.PhotoImage(pil_Image, master=boxRoot)
except:
msg += ImageErrorMsg % (imageFilename,
"\nThe Python Imaging Library (PIL) could not convert this file to a displayable image."
"\n\nPIL reports:\n" + exception_format())
else: # PIL is not loaded
msg += ImageErrorMsg % (imageFilename,
"\nI could not import the Python Imaging Library (PIL) to display the image.\n\n"
"You may need to install PIL\n"
"(http://www.pythonware.com/products/pil/)\n"
"to display " + ext + " image files.")
else:
msg += ImageErrorMsg % (imageFilename, "\nImage file not found.")
if tk_Image:
imageFrame = Frame(master=boxRoot)
imageFrame.pack(side=TOP, fill=BOTH)
label = Label(imageFrame,image=tk_Image)
label.image = tk_Image # keep a reference!
label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m')
# ------------- define the buttonsFrame ---------------------------------
buttonsFrame = Frame(master=boxRoot)
buttonsFrame.pack(side=TOP, fill=BOTH)
# ------------- define the entryFrame ---------------------------------
entryFrame = Frame(master=boxRoot)
entryFrame.pack(side=TOP, fill=BOTH)
# ------------- define the buttonsFrame ---------------------------------
buttonsFrame = Frame(master=boxRoot)
buttonsFrame.pack(side=TOP, fill=BOTH)
#-------------------- the msg widget ----------------------------
messageWidget = Message(messageFrame, width="4.5i", text=msg)
messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
messageWidget.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m')
# --------- entryWidget ----------------------------------------------
entryWidget = Entry(entryFrame, width=40)
bindArrows(entryWidget)
entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,TEXT_ENTRY_FONT_SIZE))
if mask:
entryWidget.configure(show=mask)
entryWidget.pack(side=LEFT, padx="3m")
entryWidget.bind("<Return>", __enterboxGetText)
entryWidget.bind("<Escape>", __enterboxCancel)
# put text into the entryWidget
entryWidget.insert(0,__enterboxDefaultText)
# ------------------ ok button -------------------------------
okButton = Button(buttonsFrame, takefocus=1, text="OK")
bindArrows(okButton)
okButton.pack(expand=1, side=LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m')
# for the commandButton, bind activation events to the activation event handler
commandButton = okButton
handler = __enterboxGetText
for selectionEvent in STANDARD_SELECTION_EVENTS:
commandButton.bind("<%s>" % selectionEvent, handler)
# ------------------ cancel button -------------------------------
cancelButton = Button(buttonsFrame, takefocus=1, text="Cancel")
bindArrows(cancelButton)
cancelButton.pack(expand=1, side=RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m')
# for the commandButton, bind activation events to the activation event handler
commandButton = cancelButton
handler = __enterboxCancel
for selectionEvent in STANDARD_SELECTION_EVENTS:
commandButton.bind("<%s>" % selectionEvent, handler)
# ------------------- time for action! -----------------
entryWidget.focus_force() # put the focus on the entryWidget
boxRoot.deiconify()
boxRoot.mainloop() # run it!
# -------- after the run has completed ----------------------------------
if root: root.deiconify()
boxRoot.destroy() # button_click didn't destroy boxRoot, so we do it now
return __enterboxText
def __enterboxGetText(event):
global __enterboxText
__enterboxText = entryWidget.get()
boxRoot.quit()
def __enterboxRestore(event):
global entryWidget
entryWidget.delete(0,len(entryWidget.get()))
entryWidget.insert(0, __enterboxDefaultText)
def __enterboxCancel(event):
global __enterboxText
__enterboxText = None
boxRoot.quit()
def denyWindowManagerClose():
""" don't allow WindowManager close
"""
x = Tk()
x.withdraw()
x.bell()
x.destroy()
#-------------------------------------------------------------------
# multchoicebox
#-------------------------------------------------------------------
def multchoicebox(msg="Pick as many items as you like."
, title=" "
, choices=()
, **kwargs
):
"""
Present the user with a list of choices.
allow him to select multiple items and return them in a list.
if the user doesn't choose anything from the list, return the empty list.
return None if he cancelled selection.
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed
"""
if len(choices) == 0: choices = ["Program logic error - no choices were specified."]
global __choiceboxMultipleSelect
__choiceboxMultipleSelect = 1
return __choicebox(msg, title, choices)
#-----------------------------------------------------------------------
# choicebox
#-----------------------------------------------------------------------
def choicebox(msg="Pick something."