-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gui.py
1366 lines (1035 loc) · 39.3 KB
/
Gui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""
This module is part of Swampy, a suite of programs available from
allendowney.com/swampy.
Copyright 2005 Allen B. Downey
Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.
Wrapper classes for use with tkinter.
This module provides the following classes:
Gui: a sublass of Tk that provides wrappers for most of the
widget-creating methods from Tk. The advantage of these wrappers is
that they use Python's optional argument capability to provide
appropriate default values, and that they combine widget creation and
packing into a single step. They also eliminate the need to name the
parent widget explicitly by keeping track of a current frame and
packing new objects into it.
GuiCanvas: a subclass of Canvas that provides wrappers for most of the
item-creating methods from Canvas. The advantage of the wrappers
is, again, that they use optional arguments to provide appropriate
defaults, and that they perform coordinate transformations.
Transform: an abstract class that provides basic methods inherited
by CanvasTransform and the other transforms.
CanvasTransform: a transformation that maps standard Cartesian
coordinates onto the 'graphics' coordinates used by Canvas objects.
Callable: the standard recipe from Python Cookbook for encapsulating
a function and its arguments in an object that can be used as a
callback.
The most important idea in this module is using a stack of frames to
avoid keeping track of parent widgets explicitly.
WIDGET WRAPPERS:
The Gui class contains wrappers for the widgets in tkinter.
All of the wrappers invoke widget() to create and pack the new widget.
The first four positional
arguments determine how the widget is packed. Some widgets
take additional positional arguments. In most cases, the
keyword arguments are passed as options to the widget
constructor.
Widgets that use these defaults can just pass along
args and options unmolested. Widgets (like fr and en)
that want different defaults have to roll the arguments
in with the other options and then underride them
(underride means set only if not already set).
ITEM WRAPPERS:
GuiCanvas provides wrappers for the canvas item methods.
"""
import os
import math
import sys
import Tkinter
import tkFont
from PIL import Image
from Tkinter import N, S, E, W
from Tkinter import TOP, BOTTOM, LEFT, RIGHT, END, ALL
class Gui(Tkinter.Tk):
"""Provides wrappers for many of the methods in the Tk class.
Keeps track of the current frame so that
you can create new widgets without naming the parent frame
explicitly.
"""
def __init__(self, debug=False):
"""Initializes the gui.
Turning on debugging changes the behavior of Gui.fr so
that the nested frame structure is apparent.
Attributes:
debug: is a boolean that makes Frames visible if True.
frame: is the current Frame.
frames: is the stack of pending Frames.
"""
Tkinter.Tk.__init__(self)
self.debug = debug
self.frame = self
self.frames = []
def pushfr(self, frame):
"""Pushes a frame onto the frame stack."""
self.frames.append(self.frame)
self.frame = frame
def endfr(self):
"""Ends the current frame (and returns the new current frame)."""
self.frame = self.frames.pop()
return self.frame
"""Synonyms for endfr."""
popfr = endfr
endgr = endfr
endrow = endfr
endcol = endfr
def tl(self, **options):
"""Makes and returns a top level window."""
return Tkinter.Toplevel(**options)
def fr(self, *args, **options):
"""Makes and returns a frame.
The new frame becomes the current frame.
By default, frames use the pack geometry manager, unless
self.gridding=True.
"""
if self.debug:
override(options, bd=5, relief=Tkinter.RIDGE)
# create the new frame and push it onto the stack
frame = self.widget(Tkinter.Frame, **options)
self.pushfr(frame)
return frame
def row(self, weights=[], **options):
"""Makes a frame that lays out widgets in a single row."""
return self.gr(10000, weights, [1], **options)
def col(self, weights=[], **options):
"""Makes a frame that lays out widgets in a single column."""
return self.gr(1, [1], weights, **options)
def gr(self, cols, cweights=[], rweights=[], **options):
"""Makes a frame and switches to grid mode.
(cols) is the number of columns in the grid.
(cweights) and (rweights) control how the widgets expand
if the frame expands (see colweights
and rowweights below). By default, the first 8 rows and
columns are set to expand.
(options) is a dictionary that is underridden and passed along.
"""
fr = self.fr(**options)
fr.gridding = True
fr.cols = cols
fr.i = 0
fr.j = 0
fr.cweights = cweights
fr.rweights = rweights
self.colweights(cweights)
self.rowweights(rweights)
return fr
def colweights(self, weights):
"""Attaches weights to the columns of the current grid.
Args:
weights: list of values, assigned to columns starting with 0.
These weights control how the columns in the grid expand
when the grid expands. The default weight is 0, which
means that the column doesn't expand. If only one
column has a value, it gets all the extra space.
"""
for i, weight in enumerate(weights):
self.frame.columnconfigure(i, weight=weight)
def rowweights(self, weights):
"""Attaches weights to the rows of the current grid.
Args:
weights: is a list of values, which are assigned to
rows starting with 0.
These weights control how the rows in the grid expand
when the grid expands. The default weight is 0, which
means that the row doesn't expand. If only one
row has a value, it gets all the extra space.
"""
for i, weight in enumerate(weights):
self.frame.rowconfigure(i, weight=weight)
def colweight(self, i, weight):
"""Assigns (weight) to column (i)."""
self.frame.columnconfigure(i, weight=weight)
def rowweight(self, i, weight):
"""Assigns (weight) to row (i)."""
self.frame.rowconfigure(i, weight=weight)
def grid(self, widget, i=None, j=None, **options):
"""Packs the given widget in the current grid.
By default, the widget is packed in the next available
space, but parameters i and j can specify the row
and column explicitly.
"""
if i == None: i = self.frame.i
if j == None: j = self.frame.j
widget.grid(row=i, column=j, **options)
# increment j by 1, or by columnspan
# if the widget spans more than one column.
try:
incr = options['columnspan']
except KeyError:
incr = 1
# if the user didn't specify row or column weights,
# fill them in with ones as we go along
self.frame.j += 1
if self.frame.cweights == []:
self.colweight(j, 1)
if self.frame.j == self.frame.cols:
self.frame.j = 0
self.frame.i += 1
if self.frame.rweights == []:
self.rowweight(i, 1)
def en(self, **options):
"""Makes an entry widget."""
# pull the text option out
text = options.pop('text', '')
# create the entry and insert the text
en = self.widget(Tkinter.Entry, **options)
en.insert(0, text)
return en
def ca(self, width=100, height=100, **options):
"""Makes a canvas widget."""
return self.widget(GuiCanvas, width=width, height=height, **options)
def la(self, text='', **options):
"""Makes a label widget."""
return self.widget(Tkinter.Label, text=text, **options)
def lb(self, **options):
"""Makes a listbox."""
return self.widget(Tkinter.Listbox, **options)
def bu(self, text='', command=None, **options):
"""Makes a button"""
return self.widget(Tkinter.Button, text=text, command=command,
**options)
def mb(self, **options):
"""Makes a menubutton"""
underride(options, relief=Tkinter.RAISED)
mb = self.widget(Tkinter.Menubutton, **options)
mb.menu = Tkinter.Menu(mb, tearoff=False)
mb['menu'] = mb.menu
return mb
def mi(self, mb, text='', **options):
"""Makes a menu item"""
mb.menu.add_command(label=text, **options)
def te(self, **options):
"""Makes a text entry"""
return self.widget(Tkinter.Text, **options)
def sb(self, **options):
"""Makes a text scrollbar"""
return self.widget(Tkinter.Scrollbar, **options)
def cb(self, **options):
"""Makes a checkbutton."""
# if the user didn't provide a variable, create one
try:
var = options['variable']
except KeyError:
var = Tkinter.IntVar()
override(options, variable=var)
w = self.widget(Tkinter.Checkbutton, **options)
w.swampy_var = var
return w
def rb(self, **options):
"""Makes a radiobutton"""
w = self.widget(Tkinter.Radiobutton, **options)
w.swampy_var = options['variable']
w.swampy_val = options['value']
return w
class ScrollableText(object):
"""A frame with a text entry and a scrollbar."""
def __init__(self, gui, **options):
self.frame = gui.row(**options)
self.text = gui.te(wrap=Tkinter.WORD)
self.scrollbar = gui.sb(command=self.text.yview)
self.text.configure(yscrollcommand=self.scrollbar.set)
gui.endrow()
def st(self, **options):
"""Makes a scrollable text entry."""
return Gui.ScrollableText(self, **options)
class ScrollableCanvas(object):
"""A grid with a canvas and two scrollbars."""
def __init__(self, gui, width=200, height=200, **options):
self.grid = gui.gr(2, **options)
self.canvas = gui.ca(width=width, height=height, bg='white')
self.yb = gui.sb(command=self.canvas.yview, sticky=N+S)
self.xb = gui.sb(command=self.canvas.xview,
orient=Tkinter.HORIZONTAL,
sticky=E+W)
self.canvas.configure(xscrollcommand=self.xb.set,
yscrollcommand=self.yb.set,
scrollregion=(0, 0, 400, 400))
gui.endgr()
def sc(self, **options):
"""Makes a scrollable canvas.
The options provided apply to the frame only;
if you want to configure the other widgets, you have to do
it after invoking st.
"""
return Gui.ScrollableCanvas(self, **options)
def widget(self, constructor, **options):
"""Makes a widget of the given type.
options is split into widget options, pack options and grid options.
Args:
constructor: function called to build the new widget.
options: option dictionary
Returns:
new widget
"""
underride(options, fill=Tkinter.BOTH, expand=1, sticky=N+S+E+W)
# roll the positional arguments into the option dictionary,
# then divide into options for the widget constructor, pack
# or grid
widopt, packopt, gridopt = split_options(options)
# Makes the widget and either pack or grid it
widget = constructor(self.frame, **widopt)
if hasattr(self.frame, 'gridding'):
self.grid(widget, **gridopt)
else:
widget.pack(**packopt)
return widget
def pop_options(options, names):
"""Remove the given keys from options.
Return a new dictionary with those key-value pairs.
Args:
options: dictionary
names: list of keys.
Returns:
dict
"""
new = {}
for name in names:
if name in options:
new[name] = options.pop(name)
return new
def get_options(options, names):
"""Returns a dictionary with options for the given keys.
Args:
options: dict
names: list of keys
Returns:
dict
"""
new = {}
for name in names:
if name in options:
new[name] = options[name]
return new
def remove_options(options, names):
"""Removes options from the dictionary.
Modifies options.
Args:
options: dict
names: list of keys
"""
for name in names:
if name in options:
del options[name]
def split_options(options):
"""Splits an options dictionary into into pack options and grid options.
Anything left is assumed to be a widget option
Args:
options: dict
Returns: tuple of (widget options, pack options, grid options)
"""
packnames = ['side', 'fill', 'expand', 'anchor',
'padx', 'pady', 'ipadx', 'ipady']
gridnames = ['column', 'columnspan', 'row', 'rowspan',
'padx', 'pady', 'ipadx', 'ipady', 'sticky']
# some options appear in both packopts
# and gridopts, so that's why I didn't use pop_options.
packopts = get_options(options, packnames)
gridopts = get_options(options, gridnames)
widgetopts = dict(options)
remove_options(widgetopts, packopts)
remove_options(widgetopts, gridopts)
return widgetopts, packopts, gridopts
def underride(d, **kwds):
"""Adds entries from (kwds) to (d) only if they are not already set."""
for key, val in kwds.iteritems():
d.setdefault(key, val)
def override(d, **kwds):
"""Adds entries from (kwds) to (d) even if they are already set."""
d.update(kwds)
class BBox(list):
"""List of coordinates, where each coordinate is a pair or a Point.
The first coordinate is the upper-left corner; the second pair is
the lower-right.
Assumes pixel coordinates; that is, a higher y-value is lower.
Creating a new bounding box makes a _shallow_ copy of
the list of coordinates. For a deep copy, use Bbox.copy().
"""
__slots__ = ()
def copy(self):
t = [Point(coord) for coord in self]
return BBox(t)
# top, bottom, left, and right can be accessed as attributes
def setleft(self, val): self[0][0] = val
def settop(self, val): self[0][1] = val
def setright(self, val): self[1][0] = val
def setbottom(self, val): self[1][1] = val
left = property(lambda self: self[0][0], setleft)
top = property(lambda self: self[0][1], settop)
right = property(lambda self: self[1][0], setright)
bottom = property(lambda self: self[1][1], setbottom)
def width(self):
"""Returns the width of the bbox."""
return self.right - self.left
def height(self):
"""Returns the height of the bbox."""
return self.bottom - self.top
def upperleft(self):
"""Returns the first corner of the bbox.
Usually the upper left
"""
return Point(self[0])
def lowerright(self):
"""Returns the second corner of the bbox.
Usually the lower right
"""
return Point(self[1])
def midright(self):
"""Returns the midpoint of the right edge as a Point object."""
x = self.right
y = (self.top + self.bottom) / 2.0
return Point([x, y])
def midleft(self):
"""Returns the midpoint of the left edge as a Point object."""
x = self.left
y = (self.top + self.bottom) / 2.0
return Point([x, y])
def center(self):
"""Returns the midpoint of the bbox as a Point object."""
x = (self.left + self.right) / 2.0
y = (self.top + self.bottom) / 2.0
return Point([x, y])
def union(self, other):
"""Returns a new bbox that covers self and other.
Assumes that the positive y direction is UP.
"""
left = min(self.left, other.left)
right = max(self.right, other.right)
top = max(self.top, other.top)
bottom = min(self.bottom, other.bottom)
return BBox([[left, top], [right, bottom]])
def offset(self, pos):
"""Returns the vector between the upper-left corner of self and pos.
Args:
pos: Point object or coordinate tuple.
Returns:
Point
"""
return Point([pos[0]-self.left, pos[1]-self.top])
def pos(self, offset):
"""Returns the position at the given offset from the upper-left"""
return Point([offset[0]+self.left, offset[1]+self.top])
def flatten(self):
"""Returns a list of four coordinates."""
return self[0] + self[1]
class Point(list):
"""A list of coordinates.
Because Point inherits __init__ from list, it makes a copy
of the argument to the constructor.
"""
__slots__ = ()
copy = lambda pos: Point(pos)
# x and y can be accessed as attributes
def setx(pos, val): pos[0] = val
def sety(pos, val): pos[1] = val
x = property(lambda pos: pos[0], setx)
y = property(lambda pos: pos[1], sety)
# pairiter, pair and flatten are utilities for dealing with
# lists of coordinates
def pairiter(seq):
"""Returns an iterator that yields consecutive pairs from seq."""
it = iter(seq)
while True:
yield [it.next(), it.next()]
def pair(seq):
"""Returns a list of consecutive pairs from seq."""
return [x for x in pairiter(seq)]
def flatten(seq):
"""Concatenates the elements of seq.
Given a list of lists, returns a new list that concatentes
the elements of (seq). This just does one level of flattening;
it is not recursive.
"""
return sum(seq, [])
class GuiCanvas(Tkinter.Canvas):
"""A wrapper for the Canvas provided by Tkinter.
The primary difference is that it supports coordinate
transformations, the most common of which is the CanvasTranform,
which makes canvas coordinates Cartesian (origin in the middle,
positive y axis going up).
It also provides methods like circle that provide a
nice interface to the underlying canvas methods.
The item-creating methods all return Item objects (as opposed
to Tkinter tags) so you can perform subsequent operations by
invoking methods on the Items, rather than the Canvas.
"""
def __init__(self, w, scale=[1,1], transforms=None, **options):
Tkinter.Canvas.__init__(self, w, **options)
if transforms != None:
self.transforms = transforms
else:
self.transforms = [CanvasTransform(self, scale)]
def get_width(self):
"""Gets the nominal width of this canvas."""
x = int(self.cget('width'))
# winfo would return the actual width
# x = self.winfo_width()
return x
def get_height(self):
"""Gets the nominal height of this canvas."""
x = int(self.cget('height'))
# winfo would return the actual height
# x = self.winfo_height()
return x
"""Width and height are available as read-only attributes."""
width = property(get_width)
height = property(get_height)
def clear_transforms(self):
"""Removes all existing transforms."""
self.transforms = []
def add_transform(self, transform, index=None):
"""Add a transform.
Args:
transform: Transform object
index: where in the list to insert it; appending is the default.
"""
if index == None:
self.transforms.append(transform)
else:
self.transforms.insert(index, transform)
def trans(self, coords):
"""Applies each of the transforms for this canvas, in order."""
for trans in self.transforms:
coords = trans.trans_list(coords)
return coords
def invert(self, coords):
"""Applies the inverse of each transforms, in reverse order."""
t = self.transforms[::-1]
for trans in t:
coords = trans.invert_list(coords)
return coords
def canvas_coords(self, coords):
"""Convert a position from pixel coordinates to Canvas coordinates.
Args:
coords: Point object or list of coordinates.
"""
return self.invert(coords)
def canvas_itemcoords(self, item, coords=None):
"""Gets and sets item coordinates, with translation.
Args:
item: tag of a canvas item
coords: Point object or list of coordinates
"""
if coords != None:
# set coords
coords = self.trans(coords)
coords = flatten(coords)
Tkinter.Canvas.coords(self, item, *coords)
else:
#get the coordinates and invert them
coords = Tkinter.Canvas.coords(self, item)
coords = pair(coords)
coords = self.invert(coords)
return coords
def translate_event(self, event):
"""Translates event strings into a canonical form.
Args:
event: Tkinter event string
Returns:
Tkinter event string
"""
translator = {}
for i in ['1', '2', '3']:
translator['<Press-'+i+'>'] = '<ButtonPress-' + i + '>'
translator['<Motion-'+i+'>'] = '<B' + i + '-Motion>'
translator['<Release-'+i+'>'] = '<ButtonRelease-' + i + '>'
translator['<Double-'+i+'>'] = '<Double-Button-' + i + '>'
return translator.get(event, event)
def clear(self):
"""Deletes all items on the canvas."""
self.delete('all')
def bbox(self, item):
"""Compute the bounding box of the given item.
Transforms from pixel coordinates to canvas coordinates.
Args:
item: tag of a canvas item
Returns:
Bbox object in canvas coordinates.
"""
if isinstance(item, list):
item = item[0]
# call the super
bbox = Tkinter.Canvas.bbox(self, item)
if bbox == None:
return bbox
bbox = pair(bbox)
bbox = self.invert(bbox)
return BBox(bbox)
def scroll_config(self, tag=Tkinter.ALL):
"""Configure the canvas so the scroll region covers the given tag."""
bbox = Tkinter.Canvas.bbox(self, tag)
self.configure(scrollregion=bbox)
def move(self, item, dx, dy, transform=False):
"""Moves an item on the canvas.
Args:
item: string tag of a canvas item
dx: distance to move on the x axis
dy: distance to move on the y axis
transform: boolean, whether to transform dx, dy
"""
if transform:
coords = [[0,0], [dx,dy]]
p1, p2 = self.trans(coords)
dx = p2.x - p1.x
dy = p2.y - p1.y
Tkinter.Canvas.move(self, item, dx, dy)
# the following are wrappers for the item creation methods
# inherited from the Canvas class.
def arc(self, coords, start=0, extent=90, fill='', **options):
"""Makes an arc item.
with bounding box (coords), sweeping out angle
(extent) starting at (start) both in degrees.
"""
tag = self.create_arc(self.trans(coords), options,
start=start, extent=extent, fill=fill)
return Item(self, tag)
def bitmap(self, coord, bitmap, **options):
"""Makes a bitmap item.
with the given bitmap at the given position.
The default anchor is center.
"""
tag = self.create_bitmap(self.trans([coord]), options, bitmap=bitmap)
return Item(self, tag)
def image(self, coord, image, **options):
"""Makes an image item.
with the given image at the given position.
The default anchor is center.
"""
tag = self.create_image(self.trans([coord]), options, image=image)
return Item(self, tag)
def line(self, coords, fill='black', **options):
"""Makes a polyline.
with vertices at each point in (coords)
and pen color (fill).
"""
tag = self.create_line(self.trans(coords), options, fill=fill)
return Item(self, tag)
def oval(self, coords, fill='', **options):
"""Makes an oval.
with bounding box (coords) and fill color (fill)
"""
tag = self.create_oval(self.trans(coords), options, fill=fill)
return Item(self, tag)
def circle(self, coord, r, fill='', **options):
"""Makes a circle.
with center at (x, y) and radius (r)
"""
x, y = coord
coords = self.trans([[x-r, y-r], [x+r, y+r]])
tag = self.create_oval(coords, options, fill=fill)
return Item(self, tag)
def polygon(self, coords, fill='', **options):
"""Makes a closed polygon.
with vertices at each point in (coords)
and fill color (fill).
"""
tag = self.create_polygon(self.trans(coords), options, fill=fill)
return Item(self, tag)
def rectangle(self, coords, fill='', **options):
"""Makes an oval.
with bounding box (coords) and fill color (fill)
"""
tag = self.create_rectangle(self.trans(coords), options, fill=fill)
return Item(self, tag)
def text(self, coord, text='', fill='black', **options):
"""Makes a text item.
with the given text and fill color.
The default anchor is center.
"""
tag = self.create_text(self.trans([coord]), options,
text=text, fill=fill)
return Item(self, tag)
def window(self, coord, widget, **options):
"""Embeds a window (widget) in the canvas at the given coord."""
tag = self.create_text(self.trans([coord]), options, window=widget)
return Item(self, tag)
def dump(self, filename='canvas.eps'):
"""
Creates a PostScipt file and dumps the contents of the canvas.
Then converts the EPS file to JPG, and deletes the EPS file.
"""
bbox = Tkinter.Canvas.bbox(self, ALL)
if bbox:
x, y, width, height = bbox
else:
x, y, width, height = 0, 0, 100, 100
width -= x
height -= y
ps = self.postscript(x=x, y=y, width=width, height=height)
fp = open(filename, 'w')
fp.write(ps)
fp.close()
eps_img = Image.open(filename)
jpg_img = filename[:-4] + ".jpg"
eps_img.save(jpg_img)
os.remove(filename)
class Item(object):
"""Represents a canvas item.
When you create a canvas item, Tkinter returns an integer 'tag'
that identifies the new item. To perform an operation on the
item, you invoke a method on the canvas and pass the tag as
a parameter.
The Item class makes this interface more object-oriented:
each Item object contains a canvas and a tag. When you
invoke methods on the Item, it invokes methods on its canvas.
"""
def __init__(self, canvas, tag):
self.canvas = canvas
self.tag = tag
def __str__(self):
return str(self.tag)
# the following are wrappers for canvas methods
def delete(self):
"""Deletes this item from the canvas."""
self.canvas.delete(self.tag)
def cget(self, *args):
"""Looks up the value of the given option for this item."""
return self.canvas.itemcget(self.tag, *args)
def config(self, **options):
"""Reconfigures this item with the given options."""
self.canvas.itemconfig(self.tag, **options)
def coords(self, *args):
"""Gets or sets the canvas coordinates for this item."""
return self.canvas.canvas_itemcoords(self.tag, *args)
def bbox(self):
"""Get the approximate bounding box for this item.
Returns:
BBox object in canvas coordinates.
"""
return self.canvas.bbox(self.tag)
def bind(self, event, *args):
"""Applies a binding to this item.
args can be (event, callback) or (event, callback, '+')
For the event specifier, you can use Tkinter format,
as in <Button-1>, or you can leave out the angle brackets.
"""
if event[0] != '<':
event = '<' + event + '>'
event = self.canvas.translate_event(event)
self.canvas.tag_bind(self.tag, event, *args)
def unbind(self, *args):
"""Removes bindings from this items."""
self.canvas.tag_unbind(self.tag, *args)
def type(self):
"""Returns a string indicating the type of this item."""
return self.canvas.type(self.tag)
def lift(self):
"""Raises this item to the top of the pile."""
return self.canvas.lift(self.tag)
def lower(self):
"""Lowers this item to the bottom of the pile."""
return self.canvas.lower(self.tag)
def move(self, dx, dy):
"""Moves this item by (dx, dy) in canvas coordinates."""
self.canvas.move(self.tag, dx, dy)
def move_coord(self, i, dx, dy):
"""Moves the ith coordinate by (dx, dy) in canvas coordinates."""
coords = self.coords()
coords[i][0] += dx
coords[i][1] += dy
self.coords(coords)
def replace_coord(self, i, coord):
"""Replaces the ith coordinate with the given coordinate."""
coords = self.coords()
coords[i] = coord
self.coords(coords)
def scale(self, scale, offset):
"""Shifts and scales the coordinates of this item.
Shifts by -(offset) and multiplies by (scale)
"""
xscale, yscale = scale
xoffset, yoffset = offset
self.canvas.scale(self.tag, xscale, yscale, xoffset, yoffset)
class Transform(object):
"""Provides methods for transforming lists of coordinates.
Subclasses should implement trans() and invert().
"""
def trans_list(self, points, func=None):
"""Applies (func) to a list of points.
If (func) is none, applies self.trans.
"""
if func == None:
func = self.trans
if isinstance(points[0], (list, tuple)):
return [Point(func(p)) for p in points]
else:
return Point(func(points))
def invert_list(self, points):
"""Applies the inverse transform to the list of points."""
return self.trans_list(points, self.invert)