-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheasy_draw.py
1644 lines (1531 loc) · 67.3 KB
/
easy_draw.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
#######################
# Hi students,
# DO NOT MESS AROUND WITH THIS FILE
# Please 😁
#######################
#######################
# Easy Draw Module
# Version 1.1.1
# Created by Joe Mazzone
# Documentation: https://easy-draw.joemazzone.net/
#######################
#######################
# This module was developed for students to easily create basic Python
# GUIs by drawing graphics primitives. It features drawing functions
# for many shapes, as well as event handling for basic animations and games.
#######################
# Easy Draw Docstring
"""
Easy Draw module - Objects and function to easily create drawings.
Objects:
- Rectangle
- RegPolygon
- Polygon
- Line
- Arc
- Circle
- Oval
- Text
- Image
Functions:
- load_canvas()
- end()
- set_canvas_color()
- save_canvas()
- canvas_event_setup()
- open_image()
- rgb_convert()
"""
import tkinter as tk
from tkinter import ttk
import tkinter.colorchooser, tkinter.messagebox, tkinter.simpledialog
from PIL import ImageGrab
import math
import time
import platform
class __EasyDrawError(Exception):
"""Raised for error caused by not properly using Easy Draw."""
def __init__(self, message="Seems you did something you shouldn't with Easy Draw..."):
self.message = message
super().__init__(self.message)
print("Welcome to Easy Draw! -- version 1.1.1 -- https://easy-draw.joemazzone.net/")
os = platform.system()
print("Your OS is identified as " + os)
WINDOW = None
CANVAS = None
GRID_LINES = []
grid_on = False
grid_btn_style = None
btn_style = None
POINTS_LIST_ERROR = __EasyDrawError(
message="The points_list must have an even number of values as it should contain xy coordinate pairs.")
LINE_COORDINATES_ERROR = __EasyDrawError(
message="You must use xy1 and xy2 OR a points_list to create a line.")
LINE_STYLE_ERROR = __EasyDrawError(
message="Line only supports \"round\" and \"cut\" as a style")
def load_canvas(background=None):
"""
Opens Easy Draw window with a 600x600px canvas.
Must be called before instantiating drawing objects.
"""
global WINDOW
global CANVAS
global GRID_LINES
global grid_on
global btn_style
global grid_btn_style
WINDOW = tk.Tk()
WINDOW.title("Easy Draw")
WINDOW.resizable(False, False)
grid_btn_style = ttk.Style()
btn_style = ttk.Style()
y_labels = []
x_labels = []
WINDOW.columnconfigure(1, minsize=40)
for i in range(2, 13):
WINDOW.columnconfigure(i, minsize=50)
WINDOW.rowconfigure(3, minsize=40)
for i in range(4, 15):
WINDOW.rowconfigure(i, minsize=50)
colorDialog = tkinter.colorchooser.Chooser()
def openColorDialog():
color = colorDialog.show()
if not color[1] is None:
tkinter.messagebox.showinfo("Your Color",
"The color you chose is: " + "\n\n" + color[1] + "\n\n" + "RBG (" + str(int(color[0][0]))
+ ", " + str(int(color[0][1])) + ", " + str(int(color[0][2])) + ")")
if os == "Darwin":
color_button = ttk.Button(
text = "Color Picker",
style = "W.TButton",
command = openColorDialog
)
else:
color_button = tk.Button(
text = "Color Picker",
font = ("Arial", 10, "bold"),
bg = "#07649E",
fg = "#FFFFFF",
command = openColorDialog
)
color_button.grid(column=1, row=1, columnspan=4, padx=5, pady=5)
def toggle_grid():
global GRID_LINES
global grid_on
global s
if grid_on:
grid_on = False
if os == "Darwin":
grid_btn_style.configure(
'G.TButton',
font = ("Arial", 10, "bold"),
background = "#07649E"
)
else:
grid_button["text"] = "Grid"
grid_button["bg"] = "#07649E"
for line in GRID_LINES:
CANVAS.itemconfig(line, state = tk.HIDDEN)
for label in x_labels:
label.configure(fg = WINDOW.cget("background"))
for label in y_labels:
label.configure(fg = WINDOW.cget("background"))
else:
grid_on = True
if os == "Darwin":
grid_btn_style.configure(
'G.TButton',
font = ("Arial", 10, "bold"),
background = "#E32636"
)
else:
grid_button["text"] = "Grid"
grid_button["bg"] = "#E32636"
for line in GRID_LINES:
CANVAS.itemconfig(line, state = tk.DISABLED)
for label in x_labels:
label.configure(fg = "#07649E")
for label in y_labels:
label.configure(fg = "#07649E")
if os == "Darwin":
grid_button = ttk.Button(
text="Grid",
style = "G.TButton",
command=toggle_grid
)
else:
grid_button = tk.Button(
text="Grid",
font=("Arial", 10, "bold"),
bg = "#07649E",
fg = "#FFFFFF",
command=toggle_grid
)
grid_button.grid(column=5, row=1, columnspan=4, padx=5, pady=5)
CANVAS = tk.Canvas(width = 595, height = 595, bg=background, bd=2, cursor="crosshair", relief="ridge")
CANVAS.grid(column=1, row=3, columnspan=13, rowspan=13, padx=5, sticky="nw")
if os == "Darwin":
save_button = ttk.Button(
text="Save Canvas",
style = "W.TButton",
command=save_canvas
)
else:
save_button = tk.Button(
text="Save Canvas",
font=("Arial", 10, "bold"),
bg = "#07649E",
fg = "#FFFFFF",
command=save_canvas
)
save_button.grid(column=9, row=1, columnspan=4, padx=5, pady=5)
# Display Coordinates
def mousePosition(event):
xy_label["text"] = " x , y \n(" + str(event.x) + ", " + str(event.y) + ")"
CANVAS.bind("<Motion>", mousePosition)
xy_label = tk.Label(
text = " x , y \n(0, 0)",
fg = "#07649E",
font=("Arial", 12, "bold")
)
xy_label.grid(column=8, row=16, columnspan=6, sticky="ne", padx=5, pady=5)
window_bg = WINDOW.cget("background")
for i in range(0, 601, 50):
x_labels.append(tk.Label(text = str(i), fg = window_bg, font=("Arial", 8), padx=0, pady=0))
y_labels.append(tk.Label(text = " " + str(i), fg = window_bg, font=("Arial", 8), padx=0, pady=0))
count = 1
for label in x_labels:
label.grid(column=count, row=2, sticky="sw")
count += 1
count = 3
for label in y_labels:
label.grid(column=0, row=count, sticky="ne")
count += 1
spacer1 = tk.Label(text = " ", font=("Arial", 2))
spacer1.grid(column=15, row=3, sticky="w", padx=6)
btn_style.configure(
'W.TButton',
font = ("Arial", 10, "bold"),
background = "#07649E"
)
grid_btn_style.configure(
'G.TButton',
font = ("Arial", 10, "bold"),
background = "#07649E"
)
def set_canvas_color(color):
"""Used to set the background color of the drawing canvas."""
global CANVAS
if type(color) is tuple:
color = rgb_convert(color)
CANVAS.configure(bg = color)
def end():
"""
Every Easy Draw program must end with this function call.
Sets up event loop and other important aspects of Easy Draw.
"""
global CANVAS
global WINDOW
global GRID_LINES
# Create Grid Lines
for i in range(50, 600, 50):
GRID_LINES.append(CANVAS.create_line(0, i, 610, i, fill="#C2CCD0", width=1))
for i in range(50, 600, 50):
GRID_LINES.append(CANVAS.create_line(i, 0, i, 610, fill="#C2CCD0", width=1))
for line in GRID_LINES:
CANVAS.itemconfig(line, state = tk.HIDDEN)
WINDOW.mainloop()
def __screenshot__(filename):
"""Should only be used internally! Grabs canvas image."""
global WINDOW
global CANVAS
global grid_on
x = WINDOW.winfo_rootx() + CANVAS.winfo_x()
y = WINDOW.winfo_rooty() + CANVAS.winfo_y()
x1 = x + CANVAS.winfo_width()
y1 = y + CANVAS.winfo_height()
print("Saving " + filename + ".png ", end="")
for i in range(5):
WINDOW.after(250, print(".", end=""))
print("")
ImageGrab.grab().crop((x,y,x1,y1)).save(filename + ".png")
if grid_on:
for line in GRID_LINES:
CANVAS.itemconfig(line, state = tk.NORMAL)
def save_canvas(name = None):
"""Used to save the canvas without pressing the save button."""
global WINDOW
global CANVAS
global GRID_LINES
for line in GRID_LINES:
CANVAS.itemconfig(line, state = tk.HIDDEN)
if name is None:
name = tkinter.simpledialog.askstring("Save File", "What would you like your picture's file name to be?")
if (not name is None) and (name != ""):
WINDOW.after(500, __screenshot__(name))
def canvas_event_setup(event, handler):
"""Used to setup an event for the entire canvas and not just a drawing object."""
global CANVAS
CANVAS.bind_all(event, handler)
def rgb_convert(rgb):
"""Used to convert an RGB color value to hex."""
if len(rgb) != 3:
raise __EasyDrawError(message = "RGB colors must have 3 values.")
elif (rgb[0] >= 0 and rgb[0] <= 255) and (rgb[1] >= 0 and rgb[1] <= 255) and (rgb[2] >= 0 and rgb[2] <= 255):
return '#%02x%02x%02x' % rgb
else:
raise __EasyDrawError(message = "RGB values must be positive numbers and cannot exceed 255.")
# --- Drawing Shapes ---
class Rectangle:
"""
Draws a rectangle from the top-left corner (x, y) with a given width and height.
Properties
----------
xy - REQUIRED - The x and y coordinate of the rectangle's top-left corner as a tuple.
width - REQUIRED - The width of the rectangle in pixels.
height - REQUIRED - The height of the rectangle in pixels.
color - Default is black. RGB tuple color value, hexadecimal color value, or string containing color name can be used.
border_color - Default is None. Color of the border.
border_width - Default is 0px. Size of the border in pixels.
dashes - Default is None. Size of the dashes for the border in pixels.
visible - Default is True. True = Shape can be seen. False = Shape cannot be seen.
Methods
-------
.to_string() - Used to print information about an instance.
.set_property() - Used to change one of the property values of an instance.
.rotate() - Used to rotate the shape by x degrees. Negative values rotate the opposite direction.
.erase() - Used to removed the instance from the canvas.
.event_setup() - Used to bind an event and handler to the instance.
"""
def __init__(self, xy, width, height, *, color="black", border_color=None, border_width=0, dashes=None, visible=True):
global CANVAS
self.type = "Rectangle"
self.angle = 0
self.xy = xy
self.width = width
self.height = height
self.color = color
self.border_color = border_color
self.border_width = border_width
self.dashes = dashes
self.visible = visible
self.event_list = []
self.handle_list = []
points = [
self.xy[0], self.xy[1],
self.xy[0] + self.width, self.xy[1],
self.xy[0] + self.width, self.xy[1] + self.height,
self.xy[0], self.xy[1] + self.height
]
if type(self.color) is tuple:
self.color = rgb_convert(self.color)
if type(self.border_color) is tuple:
self.border_color = rgb_convert(self.border_color)
if not self.dashes is None and not type(self.dashes) is tuple:
self.dashes = (self.dashes, self.dashes)
self.ID = CANVAS.create_polygon(points, fill=self.color, outline=self.border_color, width=self.border_width, dash=self.dashes)
if self.visible:
CANVAS.itemconfig(self.ID, state = tk.NORMAL)
else:
CANVAS.itemconfig(self.ID, state = tk.HIDDEN)
def to_string(self):
"""Used to print information about an instance."""
return "Object: " + self.type + "\t ID: " + str(self.ID)
def set_property(self, *, xy=None, width=None, height=None, color=None, border_color=None, border_width=None, dashes=None, visible=None):
"""Used to change one of the property values of an instance."""
global CANVAS
if not xy is None:
self.xy = xy
if not width is None:
self.width = width
if not height is None:
self.height = height
if not color is None:
self.color = color
if type(self.color) is tuple:
self.color = rgb_convert(self.color)
if not border_color is None:
self.border_color = border_color
if type(self.border_color) is tuple:
self.border_color = rgb_convert(self.border_color)
if not border_width is None:
self.border_width = border_width
if not dashes is None:
self.dashes = dashes
if not type(self.dashes) is tuple:
self.dashes = (self.dashes, self.dashes)
if not visible is None:
self.visible = visible
self.rotate(0)
def rotate(self, angle):
"""Used to rotate the shape by x degrees. Negative values rotate the opposite direction."""
global CANVAS
global WINDOW
self.angle += angle
shape_points = [
self.xy[0], self.xy[1],
self.xy[0] + self.width, self.xy[1],
self.xy[0] + self.width, self.xy[1] + self.height,
self.xy[0], self.xy[1] + self.height
]
new_angle = math.radians(self.angle)
cos_val = math.cos(new_angle)
sin_val = math.sin(new_angle)
count = 0
point = []
points = []
for coord in shape_points:
point.append(coord)
if count % 2 == 1:
points.append(list(point))
point.clear()
count += 1
all_x = []
all_y = []
count = 0
for coord in shape_points:
if count % 2 == 0:
all_x.append(coord)
else:
all_y.append(coord)
count += 1
center_x = sum(all_x) / len(all_x)
center_y = sum(all_y) / len(all_y)
new_points = []
for x_old, y_old in points:
x_old -= center_x
y_old -= center_y
x_new = x_old * cos_val - y_old * sin_val
y_new = x_old * sin_val + y_old * cos_val
new_points.append([x_new + center_x, y_new + center_y])
old_id = self.ID
self.ID = CANVAS.create_polygon(new_points, fill=self.color, outline=self.border_color, width=self.border_width, dash=self.dashes)
CANVAS.tag_lower(self.ID, old_id)
CANVAS.delete(old_id)
if self.visible:
CANVAS.itemconfig(self.ID, state = tk.NORMAL)
else:
CANVAS.itemconfig(self.ID, state = tk.HIDDEN)
for i in range(len(self.event_list)):
CANVAS.tag_bind(self.ID, self.event_list[i], self.handle_list[i])
def erase(self):
"""Used to removed the instance from the canvas."""
CANVAS.delete(self.ID)
def event_setup(self, event, handler):
"""Used to bind an event and handler to the instance."""
global CANVAS
CANVAS.tag_bind(self.ID, event, handler)
self.event_list.append(event)
self.handle_list.append(handler)
class RegPolygon:
"""
Draws a regular polygon, n sided shape with equal sides.
Properties
----------
nsides - REQUIRED - The number of sides the polygon has.
center_xy - REQUIRED - The x and y coordinate of the polygon's center as a tuple.
radius - REQUIRED - The distance in pixels from the center to any outer point.
color - Default is black. RGB tuple color value, hexadecimal color value, or string containing color name can be used.
border_color - Default is None. Color of the border.
border_width - Default is 0px. Size of the border in pixels.
dashes - Default is None. Size of the dashes for the border in pixels.
visible - Default is True. True = Shape can be seen. False = Shape cannot be seen.
Methods
-------
.to_string() - Used to print information about an instance.
.set_property() - Used to change one of the property values of an instance.
.rotate() - Used to rotate the shape by x degrees. Negative values rotate the opposite direction.
.erase() - Used to removed the instance from the canvas.
.event_setup() - Used to bind an event and handler to the instance.
"""
def __init__(self, nsides, center_xy, radius, *, color="black", border_color=None, border_width=0, dashes=None, visible=True):
global CANVAS
self.nsides = nsides
self.type = str(self.nsides) + "-Sided Regular Polygon"
self.angle = 0
self.center_xy = center_xy
self.radius = radius
self.color = color
self.border_color = border_color
self.border_width = border_width
self.dashes = dashes
self.visible = visible
self.event_list = []
self.handle_list = []
angle = 0
angle_increment = 2*math.pi / self.nsides
points = []
for i in range(self.nsides):
x = self.center_xy[0] + self.radius * math.cos(angle)
points.append(x)
y = self.center_xy[1] + self.radius * math.sin(angle)
points.append(y)
angle += angle_increment
if type(self.color) is tuple:
self.color = rgb_convert(self.color)
if type(self.border_color) is tuple:
self.border_color = rgb_convert(self.border_color)
if not self.dashes is None and not type(self.dashes) is tuple:
self.dashes = (self.dashes, self.dashes)
self.ID = CANVAS.create_polygon(points, fill=self.color, outline=self.border_color, width=self.border_width, dash=self.dashes)
if self.visible:
CANVAS.itemconfig(self.ID, state = tk.NORMAL)
else:
CANVAS.itemconfig(self.ID, state = tk.HIDDEN)
def to_string(self):
"""Used to print information about an instance."""
return "Object: " + self.type + "\t ID: " + str(self.ID)
def set_property(self, *, nsides=None, center_xy=None, radius=None, color=None, border_color=None, border_width=None, dashes=None, visible=None):
"""Used to change one of the property values of an instance."""
global CANVAS
if not nsides is None:
self.nsides = nsides
self.type = str(self.nsides) + "-Sided Regular Polygon"
if not center_xy is None:
self.center_xy = center_xy
if not radius is None:
self.radius = radius
if not color is None:
self.color = color
if type(self.color) is tuple:
self.color = rgb_convert(self.color)
if not border_color is None:
self.border_color = border_color
if type(self.border_color) is tuple:
self.border_color = rgb_convert(self.border_color)
if not border_width is None:
self.border_width = border_width
if not dashes is None:
self.dashes = dashes
if not type(self.dashes) is tuple:
self.dashes = (self.dashes, self.dashes)
if not visible is None:
self.visible = visible
self.rotate(0)
def rotate(self, angle):
"""Used to rotate the shape by x degrees. Negative values rotate the opposite direction."""
global CANVAS
global WINDOW
self.angle += angle
draw_angle = 0
angle_increment = 2*math.pi / self.nsides
shape_points = []
for i in range(self.nsides):
x = self.center_xy[0] + self.radius * math.cos(draw_angle)
shape_points.append(x)
y = self.center_xy[1] + self.radius * math.sin(draw_angle)
shape_points.append(y)
draw_angle += angle_increment
new_angle = math.radians(self.angle)
cos_val = math.cos(new_angle)
sin_val = math.sin(new_angle)
count = 0
point = []
points = []
for coord in shape_points:
point.append(coord)
if count % 2 == 1:
points.append(list(point))
point.clear()
count += 1
all_x = []
all_y = []
count = 0
for coord in shape_points:
if count % 2 == 0:
all_x.append(coord)
else:
all_y.append(coord)
count += 1
center_x = sum(all_x) / len(all_x)
center_y = sum(all_y) / len(all_y)
new_points = []
for x_old, y_old in points:
x_old -= center_x
y_old -= center_y
x_new = x_old * cos_val - y_old * sin_val
y_new = x_old * sin_val + y_old * cos_val
new_points.append([x_new + center_x, y_new + center_y])
old_id = self.ID
self.ID = CANVAS.create_polygon(new_points, fill=self.color, outline=self.border_color, width=self.border_width, dash=self.dashes)
CANVAS.tag_lower(self.ID, old_id)
CANVAS.delete(old_id)
if self.visible:
CANVAS.itemconfig(self.ID, state = tk.NORMAL)
else:
CANVAS.itemconfig(self.ID, state = tk.HIDDEN)
for i in range(len(self.event_list)):
CANVAS.tag_bind(self.ID, self.event_list[i], self.handle_list[i])
def erase(self):
"""Used to removed the instance from the canvas."""
CANVAS.delete(self.ID)
def event_setup(self, event, handler):
"""Used to bind an event and handler to the instance."""
global CANVAS
CANVAS.tag_bind(self.ID, event, handler)
self.event_list.append(event)
self.handle_list.append(handler)
class Polygon:
"""
Draws a polygon using a list of points.
Properties
----------
points_list - REQUIRED - A list of x y coordinates identifying the points of the polygon. List must have an even number of values.
color - Default is black. RGB tuple color value, hexadecimal color value, or string containing color name can be used.
border_color - Default is None. Color of the border.
border_width - Default is 0px. Size of the border in pixels.
dashes - Default is None. Size of the dashes for the border in pixels.
visible - Default is True. True = Shape can be seen. False = Shape cannot be seen.
Methods
-------
.to_string() - Used to print information about an instance.
.set_property() - Used to change one of the property values of an instance.
.rotate() - Used to rotate the shape by x degrees. Negative values rotate the opposite direction.
.erase() - Used to removed the instance from the canvas.
.event_setup() - Used to bind an event and handler to the instance.
"""
def __init__(self, points_list, *, color="black", border_color=None, border_width=0, dashes=None, visible=True):
global CANVAS
global POINTS_LIST_ERROR
if len(points_list) % 2 != 0:
raise POINTS_LIST_ERROR
self.points_list = points_list
self.nsides = len(points_list)
self.type = str(self.nsides) + "-Sided Polygon"
self.angle = 0
self.color = color
self.border_color = border_color
self.border_width = border_width
self.dashes = dashes
self.visible = visible
self.event_list = []
self.handle_list = []
if type(self.color) is tuple:
self.color = rgb_convert(self.color)
if type(self.border_color) is tuple:
self.border_color = rgb_convert(self.border_color)
if not self.dashes is None and not type(self.dashes) is tuple:
self.dashes = (self.dashes, self.dashes)
self.ID = CANVAS.create_polygon(self.points_list, fill=self.color, outline=self.border_color, width=self.border_width, dash=self.dashes)
if self.visible:
CANVAS.itemconfig(self.ID, state = tk.NORMAL)
else:
CANVAS.itemconfig(self.ID, state = tk.HIDDEN)
def to_string(self):
"""Used to print information about an instance."""
return "Object: " + self.type + "\t ID: " + str(self.ID)
def set_property(self, *, points_list=None, color=None, border_color=None, border_width=None, dashes=None, visible=None):
"""Used to change one of the property values of an instance."""
global CANVAS
global POINTS_LIST_ERROR
if not points_list is None:
if len(points_list) % 2 != 0:
raise POINTS_LIST_ERROR
self.points_list = points_list
self.nsides = len(self.points_list)
self.type = str(self.nsides) + "-Sided Polygon"
if not color is None:
self.color = color
if type(self.color) is tuple:
self.color = rgb_convert(self.color)
if not border_color is None:
self.border_color = border_color
if type(self.border_color) is tuple:
self.border_color = rgb_convert(self.border_color)
if not border_width is None:
self.border_width = border_width
if not dashes is None:
self.dashes = dashes
if not type(self.dashes) is tuple:
self.dashes = (self.dashes, self.dashes)
if not visible is None:
self.visible = visible
self.rotate(0)
def rotate(self, angle):
"""Used to rotate the shape by x degrees. Negative values rotate the opposite direction."""
global CANVAS
global WINDOW
self.angle += angle
new_angle = math.radians(self.angle)
cos_val = math.cos(new_angle)
sin_val = math.sin(new_angle)
shape_points = self.points_list
count = 0
point = []
points = []
for coord in shape_points:
point.append(coord)
if count % 2 == 1:
points.append(list(point))
point.clear()
count += 1
all_x = []
all_y = []
count = 0
for coord in shape_points:
if count % 2 == 0:
all_x.append(coord)
else:
all_y.append(coord)
count += 1
center_x = sum(all_x) / len(all_x)
center_y = sum(all_y) / len(all_y)
new_points = []
for x_old, y_old in points:
x_old -= center_x
y_old -= center_y
x_new = x_old * cos_val - y_old * sin_val
y_new = x_old * sin_val + y_old * cos_val
new_points.append([x_new + center_x, y_new + center_y])
old_id = self.ID
self.ID = CANVAS.create_polygon(new_points, fill=self.color, outline=self.border_color, width=self.border_width, dash=self.dashes)
CANVAS.tag_lower(self.ID, old_id)
CANVAS.delete(old_id)
if self.visible:
CANVAS.itemconfig(self.ID, state = tk.NORMAL)
else:
CANVAS.itemconfig(self.ID, state = tk.HIDDEN)
for i in range(len(self.event_list)):
CANVAS.tag_bind(self.ID, self.event_list[i], self.handle_list[i])
def erase(self):
"""Used to removed the instance from the canvas."""
CANVAS.delete(self.ID)
def event_setup(self, event, handler):
"""Used to bind an event and handler to the instance."""
global CANVAS
CANVAS.tag_bind(self.ID, event, handler)
self.event_list.append(event)
self.handle_list.append(handler)
class Line:
"""
Draws a line using a starting xy coordinate and ending xy coordinate.
Properties
----------
xy1 - REQUIRED - The starting xy coordinate of the line as a tuple.
xy2 - REQUIRED - The ending xy coordinate of the line as a tuple.
color - Default is black. RGB tuple color value, hexadecimal color value, or string containing color name can be used.
thickness - Default is 5px. The width of the line.
dashes - Default is None. Size of the dashes for the border in pixels.
arrow_start - Default is False. Add an arrow to the start of the line.
arrow_end - Default is False. Add an arrow to the end of the line.
visible - Default is True. True = Shape can be seen. False = Shape cannot be seen.
Methods
-------
.to_string() - Used to print information about an instance.
.set_property() - Used to change one of the property values of an instance.
.rotate() - Used to rotate the shape by x degrees. Negative values rotate the opposite direction.
.erase() - Used to removed the instance from the canvas.
.event_setup() - Used to bind an event and handler to the instance.
"""
def __init__(self, xy1=None, xy2=None, *, points_list=None, color="black", thickness=5,
dashes=None, arrow_start=False, arrow_end=False, style="round", visible=True):
global CANVAS
global LINE_COORDINATES_ERROR
global LINE_STYLE_ERROR
global POINTS_LIST_ERROR
self.type = "Line"
self.angle = 0
if (xy1 is None or xy2 is None) and points_list is None:
raise LINE_COORDINATES_ERROR
elif points_list is None:
self.points_list = [xy1[0], xy1[1], xy2[0], xy2[1]]
else:
if len(points_list) % 2 != 0:
raise POINTS_LIST_ERROR
self.points_list = points_list
self.color = color
self.thickness = thickness
self.dashes = dashes
self.arrow_start = arrow_start
self.arrow_end = arrow_end
self.style = style
self.visible = visible
self.event_list = []
self.handle_list = []
if type(self.color) is tuple:
self.color = rgb_convert(self.color)
if not self.dashes is None and not type(self.dashes) is tuple:
self.dashes = (self.dashes, self.dashes)
if self.style.lower() == "round":
if self.arrow_start and self.arrow_end:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness, dash=self.dashes, arrow=tk.BOTH,
capstyle=tk.ROUND, joinstyle=tk.ROUND)
elif self.arrow_start:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, arrow=tk.FIRST, capstyle=tk.ROUND, joinstyle=tk.ROUND)
elif self.arrow_end:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, arrow=tk.LAST, capstyle=tk.ROUND, joinstyle=tk.ROUND)
else:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, capstyle=tk.ROUND, joinstyle=tk.ROUND)
elif self.style.lower() == "cut":
if self.arrow_start and self.arrow_end:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness, dash=self.dashes, arrow=tk.BOTH,
capstyle=tk.BUTT, joinstyle=tk.BEVEL)
elif self.arrow_start:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, arrow=tk.FIRST, capstyle=tk.BUTT, joinstyle=tk.BEVEL)
elif self.arrow_end:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, arrow=tk.LAST, capstyle=tk.BUTT, joinstyle=tk.BEVEL)
else:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, capstyle=tk.BUTT, joinstyle=tk.BEVEL)
else:
raise LINE_STYLE_ERROR
if self.visible:
CANVAS.itemconfig(self.ID, state = tk.NORMAL)
else:
CANVAS.itemconfig(self.ID, state = tk.HIDDEN)
def to_string(self):
"""Used to print information about an instance."""
return "Object: " + self.type + "\t ID: " + str(self.ID)
def set_property(self, *, points_list=None, color=None, thickness=None, dashes=None, arrow_start=None, arrow_end=None, visible=None):
"""Used to change one of the property values of an instance."""
global CANVAS
global POINTS_LIST_ERROR
if not points_list is None:
if len(points_list) % 2 != 0:
raise POINTS_LIST_ERROR
self.points_list = points_list
if not color is None:
self.color = color
if type(self.color) is tuple:
self.color = rgb_convert(self.color)
if not thickness is None:
self.thickness = thickness
if not dashes is None:
self.dashes = dashes
if not type(self.dashes) is tuple:
self.dashes = (self.dashes, self.dashes)
if not arrow_start is None:
self.arrow_start = arrow_start
if not arrow_end is None:
self.arrow_end = arrow_end
if not visible is None:
self.visible = visible
self.rotate(0)
def rotate(self, angle):
"""Used to rotate the shape by x degrees. Negative values rotate the opposite direction."""
global CANVAS
global WINDOW
global LINE_STYLE_ERROR
self.angle += angle
self.angle %= 360
new_angle = math.radians(angle)
cos_val = math.cos(new_angle)
sin_val = math.sin(new_angle)
shape_points = self.points_list
count = 0
point = []
points = []
for coord in shape_points:
point.append(coord)
if count % 2 == 1:
points.append(list(point))
point.clear()
count += 1
all_x = []
all_y = []
count = 0
for coord in shape_points:
if count % 2 == 0:
all_x.append(coord)
else:
all_y.append(coord)
count += 1
center_x = sum(all_x) / len(all_x)
center_y = sum(all_y) / len(all_y)
new_points = []
for x_old, y_old in points:
x_old -= center_x
y_old -= center_y
x_new = x_old * cos_val - y_old * sin_val
y_new = x_old * sin_val + y_old * cos_val
new_points.append(x_new + center_x)
new_points.append(y_new + center_y)
old_id = self.ID
self.points_list = new_points
if self.style.lower() == "round":
if self.arrow_start and self.arrow_end:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness, dash=self.dashes, arrow=tk.BOTH,
capstyle=tk.ROUND, joinstyle=tk.ROUND)
elif self.arrow_start:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, arrow=tk.FIRST, capstyle=tk.ROUND, joinstyle=tk.ROUND)
elif self.arrow_end:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, arrow=tk.LAST, capstyle=tk.ROUND, joinstyle=tk.ROUND)
else:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, capstyle=tk.ROUND, joinstyle=tk.ROUND)
elif self.style.lower() == "cut":
if self.arrow_start and self.arrow_end:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness, dash=self.dashes, arrow=tk.BOTH,
capstyle=tk.BUTT, joinstyle=tk.BEVEL)
elif self.arrow_start:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, arrow=tk.FIRST, capstyle=tk.BUTT, joinstyle=tk.BEVEL)
elif self.arrow_end:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, arrow=tk.LAST, capstyle=tk.BUTT, joinstyle=tk.BEVEL)
else:
self.ID = CANVAS.create_line(self.points_list, fill=self.color, width=self.thickness,
dash=self.dashes, capstyle=tk.BUTT, joinstyle=tk.BEVEL)
else:
raise LINE_STYLE_ERROR
CANVAS.tag_lower(self.ID, old_id)
CANVAS.delete(old_id)
if self.visible:
CANVAS.itemconfig(self.ID, state = tk.NORMAL)
else:
CANVAS.itemconfig(self.ID, state = tk.HIDDEN)
for i in range(len(self.event_list)):
CANVAS.tag_bind(self.ID, self.event_list[i], self.handle_list[i])
def erase(self):
"""Used to removed the instance from the canvas."""
CANVAS.delete(self.ID)
def event_setup(self, event, handler):
"""Used to bind an event and handler to the instance."""
global CANVAS
CANVAS.tag_bind(self.ID, event, handler)
self.event_list.append(event)
self.handle_list.append(handler)
class Circle:
"""
Draws a circle with a center coordinate and a radius.
Properties
----------
center_xy - REQUIRED - The center coordinate (x, y) of the circle.
radius - REQUIRED - The measurement in pixels from the center of the circle to the edge.
color - Default is black. RGB tuple color value, hexadecimal color value, or string containing color name can be used.
border_color - Default is None. Color of the border.
border_width - Default is 0px. Size of the border in pixels.
dashes - Default is None. Size of the dashes for the border in pixels.
visible - Default is True. True = Shape can be seen. False = Shape cannot be seen.
Methods
-------
.to_string() - Used to print information about an instance.
.set_property() - Used to change one of the property values of an instance.
.rotate() - Used to rotate the shape by x degrees. Negative values rotate the opposite direction.
.erase() - Used to removed the instance from the canvas.
.event_setup() - Used to bind an event and handler to the instance.
"""
def __init__(self, center_xy, radius, *, color="black", border_color=None, border_width=0, dashes=None, visible=True):
global CANVAS
self.type = "Circle"
self.angle = 0
self.center_xy = center_xy
self.radius = radius
self.color = color
self.border_color = border_color
self.border_width = border_width
self.dashes = dashes
self.visible = visible
self.event_list = []
self.handle_list = []
center_x, center_y = self.center_xy
x1 = center_x - self.radius
y1 = center_y - self.radius
x2 = center_x + self.radius
y2 = center_y + self.radius
if type(self.color) is tuple:
self.color = rgb_convert(self.color)
if type(self.border_color) is tuple:
self.border_color = rgb_convert(self.border_color)
if not self.dashes is None and not type(self.dashes) is tuple: