-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.py
1849 lines (1443 loc) · 58.7 KB
/
functions.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
import json
import logging
import os
import pickle
import random
import tkinter as tk
from colorama import init as coloramainit
coloramainit()
from tkinter import ttk, filedialog, messagebox
from Shapes.Circle import *
from Shapes.Point import *
from Shapes.Line import *
from Shapes.Polygon import Polygon
from Shapes.Segment import *
from label_generator import generate_alphanumeric_sequence, get_label_parts
import re
import config
config.label_generator = generate_alphanumeric_sequence()
from scipy.spatial import ConvexHull, Delaunay
class SidePanel(tk.Frame):
def __init__(self, parent, bool, side, pack_bool):
tk.Frame.__init__(self, parent)
self.text = tk.Text(self, wrap=tk.WORD)
self.text.configure(state="disabled")
if pack_bool:
self.text.pack(side=side, fill=tk.BOTH, expand=True)
if bool:
scrollbar = ttk.Scrollbar(self, command=self.text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.text.config(yscrollcommand=scrollbar.set)
def insert_text(self, text):
self.text.configure(state="normal") # Enable editing
self.text.insert(tk.END, text) # Insert the text at the end
self.text.configure(state="disabled") # Disable editing
def insert_block(self, texts):
for text in texts:
self.insert_text(text)
def clear_text(self):
self.text.configure(state="normal") # Enable editing
self.text.delete(1.0, tk.END) # Delete all text from the start to the end
self.text.configure(state="disabled") # Disable editing
def init_program():
width = config.root.winfo_screenwidth()
height = config.root.winfo_screenheight()
# setting tkinter window size
config.root.geometry("%dx%d" % (width, height))
config.root.wm_title("PyGeoGebra")
config.fig.set_size_inches(8, 8)
config.ax.set_xlim(-10, 10)
config.ax.set_ylim(-10, 10)
config.ax.set_aspect('equal')
config.ax.grid(True)
config.ax.set_xticks(np.arange(-20, 21, 5))
config.ax.set_yticks(np.arange(-20, 21, 5))
config.ax.axhline(0, color='black', linewidth=0.5)
config.ax.axvline(0, color='black', linewidth=0.5)
config.buttons_panel.pack(side=tk.TOP, fill=tk.X)
global button_list, file_button
def create_buttons():
global button_list, file_button
point_button = tk.Button(config.buttons_panel, text="Point", command=draw_point)
line_button = tk.Button(config.buttons_panel, text="Line", command=draw_line)
segment_button = tk.Button(config.buttons_panel, text="Segment", command=draw_segment)
circle_button = tk.Button(config.buttons_panel, text="Circle", command=draw_circle)
polygon_button = tk.Button(config.buttons_panel, text="Polygon", command=draw_polygon)
reset_button = tk.Button(config.buttons_panel, text="Reset", command=reset)
save_button = tk.Button(config.buttons_panel, text="Save", command=save)
load_button = tk.Button(config.buttons_panel, text="Load file", command=load)
delete_button = tk.Button(config.buttons_panel, text="Delete shape", command=delete_shape)
algors = tk.Button(config.buttons_panel, text="Algorithms", command=algos)
undo_button = tk.Button(config.buttons_panel, text="undo", command=undo)
redo_button = tk.Button(config.buttons_panel, text="redo", command=redo)
clear_history_button = tk.Button(config.buttons_panel, text="clear history", command=clear_history)
info_button = tk.Button(config.buttons_panel, text="Info", command=information)
buttons = [save_button,
load_button,
delete_button,
reset_button,
point_button,
line_button,
segment_button,
circle_button,
polygon_button,
algors,
# tmp,
# ix,
# file_button,
info_button,
clear_history_button,
redo_button,
undo_button]
padding = 2
right = [info_button,
clear_history_button,
undo_button,
redo_button, ]
for i in range(len(buttons)):
if buttons[i] in right:
buttons[i].pack(side=tk.RIGHT, padx=padding)
else:
buttons[i].pack(side=tk.LEFT, padx=padding)
# def show_algorithms():
# # Function to display the choices for Algorithms
# config.info_panel.config(text="Choose an algorithm:")
# choices = ["Yes", "No", "Maybe"]
# config.option_var.set(choices[0]) # Set the default choice
# config.option_menu = tk.OptionMenu(config.info_window, config.option_var, *choices)
# config.option_menu.pack(padx=10, pady=10)
# config.current_selection = "Algorithms"
#
# def show_shapes():
# # Function to display the choices for Shapes
# config.info_panel.config(text="Choose a shape:")
# choices = ["Line", "Segment", "Triangle", "Circle", "Polygon"]
# config.option_var.set(choices[0]) # Set the default choice
# config.option_menu = tk.OptionMenu(config.info_window, config.option_var, *choices)
# config.option_menu.pack(padx=10, pady=10)
# config.current_selection = "Shapes"
#
#
# def information():
# if not config.isopen_info_panel: # Check if info panel is not already open
# # Create a new window (panel) to display the message
# config.info_window = tk.Toplevel(config.root) # 'root' is the main Tkinter window
#
# # Set the window title
# config.info_window.title("Information Panel")
#
# # Create a label with the message
# config.info_panel = tk.Label(config.info_window, text="Hello")
# config.info_panel.pack(padx=10, pady=10)
#
# # Add a variable to store the selected choice
# config.option_var = tk.StringVar()
#
# # Add a variable to store the current selection
# config.current_selection = ""
#
# # Set config.isopen_info_panel to True to indicate that the panel is now open
# config.isopen_info_panel = True
#
# # Create a menu for selecting Algorithms or Shapes
# menu_choices = ["Algorithms", "Shapes"]
# config.menu_var = tk.StringVar(config.info_window)
# config.menu_var.set(menu_choices[0]) # Set the default choice
# config.menu = tk.OptionMenu(config.info_window, config.menu_var, *menu_choices, command=menu_callback)
# config.menu.pack(padx=10, pady=10)
#
#
# def menu_callback(selection):
# # Function to handle the selection from the Algorithms/Shapes menu
# if config.current_selection == selection:
# # If the same selection is chosen, do nothing
# return
#
# # Remove the existing option menu if it exists
# if hasattr(config, "option_menu"):
# config.option_menu.pack_forget()
#
# if selection == "Algorithms":
# show_algorithms()
# elif selection == "Shapes":
# show_shapes()
# def show_information():
# # Function to display the information about the chosen shape
# config.info_label = tk.Label(config.info_window, text="", font=("Arial", 12), anchor="center")
# config.info_label.pack(padx=10, pady=5)
# chosen_shape = config.option_var.get()
# info_text = f"{chosen_shape}"
# config.info_label.config(text=info_text, font=("Arial", 18, "bold"), fg="blue")
#
# # config.canvas.delete("all")
#
# # Display the corresponding image based on the selected shape
# chosen_shape = config.option_var.get()
# image = None
# if chosen_shape != "Choose":
# l = os.listdir("./Images")
# print(l)
# image = tk.PhotoImage(file=f"./Images/{chosen_shape}.png")
# config.info_window.create_image(150, 50, image=image)
#
#
# def show_shapes():
# # Function to display the choices for Shapes
# config.info_panel.config(text="Choose a shape:")
# choices = ["Choose", "Point", "Segment", "Line", "Circle", "Polygon"]
# config.option_var.set(choices[0]) # Set the default choice
# config.option_menu = tk.OptionMenu(config.info_window, config.option_var, *choices)
# config.option_menu.pack(padx=10, pady=10)
# config.current_selection = "Shapes"
#
# def on_panel_close():
# # Function to handle the event when the information panel is closed
# config.isopen_info_panel = False
# config.info_window.destroy()
# config.info_panel = None
# config.info_label = None
# config.current_selection = ""
#
#
# def information():
# if not config.isopen_info_panel:
# # Create a new window (panel) to display the message
# config.info_window = tk.Toplevel(config.root)
#
# # Set the window title
# config.info_window.title("Information Panel")
# config.info_window.geometry("400x700")
#
# # Bind the event of closing the panel window to on_panel_close function
# config.info_window.protocol("WM_DELETE_WINDOW", on_panel_close)
#
# # Create a label with the message
# config.info_panel = tk.Label(config.info_window, text="Choose a shape:")
# config.info_panel.pack(padx=10, pady=10)
#
# # Add a variable to store the selected choice
# config.option_var = tk.StringVar()
#
# # Add a variable to store the current selection
# config.current_selection = ""
#
# # Create a menu for selecting Shapes
# choices = ["Choose", "Point", "Segment", "Line", "Circle", "Polygon"]
# config.option_var.set(choices[0]) # Set the default choice
# config.option_menu = tk.OptionMenu(config.info_window, config.option_var, *choices)
# config.option_menu.pack(padx=10, pady=10)
#
#
#
# # Set config.isopen_info_panel to True to indicate that the panel is now open
# config.isopen_info_panel = True
#
# # Create a "Show Information" button
# show_info_btn = tk.Button(config.info_window, text="Load Info", command=show_information)
# show_info_btn.pack(pady=5)
from PIL import Image, ImageTk
def display_shape_information(chosen_shape):
info_file_path = f"./Info/{chosen_shape}_info.txt"
if os.path.exists(info_file_path):
with open(info_file_path, "r") as info_file:
info_text = info_file.read()
else:
info_text = f"No information available for {chosen_shape}."
config.info_label.config(text=info_text, font=("Arial", 14), fg="black")
def show_information():
config.info_label.config(text="", font=("Arial", 12), anchor="center")
chosen_shape = config.option_var.get()
info_text = f"{chosen_shape}"
config.info_label.config(text=info_text, font=("Arial", 18, "bold"), fg="blue")
display_shape_information(chosen_shape)
config.image_canvas.delete("all")
if chosen_shape != "Choose":
image_path = f"./Images/{chosen_shape}.png"
if os.path.exists(image_path):
pil_image = Image.open(image_path)
canvas_width = config.image_canvas.winfo_width()
canvas_height = config.image_canvas.winfo_height()
image_width, image_height = pil_image.size
scale_factor = min(canvas_width / image_width, canvas_height / image_height)
new_width = int(image_width * scale_factor)
new_height = int(image_height * scale_factor)
pil_image = pil_image.resize((new_width, new_height), Image.ANTIALIAS)
config.image = ImageTk.PhotoImage(pil_image)
config.image_canvas.config(width=canvas_width, height=canvas_height)
config.image_canvas.create_image((canvas_width - new_width) // 2, (canvas_height - new_height) // 2,
anchor=tk.NW, image=config.image)
else:
print(f"Image not found: {image_path}")
def on_panel_close():
config.isopen_info_panel = False
config.info_window.destroy()
config.info_panel = None
config.info_label = None
config.image_canvas = None
config.current_selection = ""
def information():
if not config.isopen_info_panel:
config.info_window = tk.Toplevel(config.root)
config.info_window.title("Information Panel")
config.info_window.geometry("900x1000")
config.info_window.protocol("WM_DELETE_WINDOW", on_panel_close)
config.info_panel = tk.Label(config.info_window, text="Choose a shape:")
config.info_panel.pack(padx=10, pady=10)
config.option_var = tk.StringVar()
config.current_selection = ""
choices = ["Choose", "Point", "Segment", "Line", "Circle", "Polygon"]
config.option_var.set(choices[0]) # Set the default choice
config.option_menu = tk.OptionMenu(config.info_window, config.option_var, *choices)
config.option_menu.pack(padx=10, pady=10)
show_info_btn = tk.Button(config.info_window, text="Load Info", command=show_information)
show_info_btn.pack(pady=5)
config.info_label = tk.Label(config.info_window, text="", font=("Arial", 12), anchor="center")
config.info_label.pack(padx=10, pady=5)
config.image_canvas = tk.Canvas(config.info_window, width=300, height=300)
config.image_canvas.pack()
config.isopen_info_panel = True
def x():
for shape in config.shapes:
if isinstance(shape, Segment):
if shape.get_label() == '':
config.shapes.remove(shape)
update_label()
update_display()
def convex(label):
config.null_segments=[]
config.conv_vx = ""
x()
points = []
shape = find_shape(label)
for segment in shape.get_segment_list():
start = segment.get_start()
end = segment.get_end()
if start not in points:
points.append(start)
if end not in points:
points.append(end)
poly = shape.graham_scan(points)
for edge_poly in poly:
# draw_shape(edge_poly)
edge_poly.draw(config.ax)
config.null_segments.append(edge_poly)
l=edge_poly.get_start().get_label()
if l not in config.conv_vx.split(", "):
if config.conv_vx == "":
config.conv_vx = l
else:
config.conv_vx = f'{config.conv_vx}, {l}'
def triangulation(label):
config.null_segments = []
shape = find_shape(label)
triangles = shape.triangulation()
for tria in triangles:
tria.draw(config.ax)
config.null_segments.append(tria)
# draw_shape(tria)
def find_shape(label):
for shape in config.shapes:
if label == shape.get_label():
return shape
return None
def activate():
config.null_segments = []
if config.bool_panel_algo:
update_display()
config.algorithms_panel.clear_text()
if not config.calc:
config.info = tk.Label(config.algorithms_panel.text, text="Information: ", font='Helvetica 25 bold')
config.info.pack(anchor='w', padx=10)
config.calc = True
chosen_algo = config.algo_var.get()
chosen_shape = config.poly_var.get()
if chosen_algo == "choose" or chosen_shape == "choose":
return
else:
shape = find_shape(chosen_shape)
type=''
if isinstance(shape, Point):
type = 'Point'
elif isinstance(shape, Line):
type = 'Line'
elif isinstance(shape, Segment):
type = 'Segment'
elif isinstance(shape, Circle):
type = 'Circle'
elif isinstance(shape, Polygon):
type = 'Polygon'
data = ['\n'*35,
f' Type: {type}\n',
f' Label: {shape.get_label()}\n'
]
config.algorithms_panel.insert_block(data)
if isinstance(shape, Point):
config.algorithms_panel.insert_text(f' Coords: ({shape.get_x():0.3f}, {shape.get_y():0.3f})\n')
elif isinstance(shape, Circle):
data = [f' Radius: {shape.get_radius():0.3f}\n',
f' Center: ({shape.get_center().get_x():0.3f}, {shape.get_center().get_y():0.3f})\n'
]
config.algorithms_panel.insert_block(data)
elif isinstance(shape, Segment) or isinstance(shape, Line):
data = [f' Start: ({shape.get_start().get_x():0.3f}, {shape.get_start().get_y():0.3f})\n',
f' End: ({shape.get_end().get_x():0.3f}, {shape.get_end().get_y():0.3f})\n'
]
config.algorithms_panel.insert_block(data)
elif isinstance(shape, Polygon):
pass
if chosen_algo == 'Perimeter':
config.algorithms_panel.insert_text(f' Perimeter: {shape.perimeter()}\n')
elif chosen_algo == 'Area':
config.algorithms_panel.insert_text(f' Area: {shape.area()}\n')
elif chosen_algo == 'Convex-hull':
convex(chosen_shape)
config.algorithms_panel.insert_text(f' Convex: {config.conv_vx}\n')
elif chosen_algo == 'Triangulation':
triangulation(chosen_shape)
return
def reset_button(bool=True):
config.null_segments = []
x()
if config.algorithms_panel is not None:
config.algorithms_panel.clear_text()
if not config.bool_panel_algo:
config.algorithms_panel.pack_forget()
config.bool_panel_algo = False
config.algo_var = None
config.poly_var = None
if bool:
algos()
def algos():
config.calc = False
if not config.bool_panel_algo:
config.algorithms_panel = SidePanel(config.root, False, tk.RIGHT, True)
config.algorithms_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=False)
config.bool_panel_algo = True
tk.Label(config.algorithms_panel.text, text="Algorithms ", bg="white",
font='Helvetica 18 bold underline').pack(anchor='w', fill=tk.BOTH)
# Add menu, text, and button
menu_label = tk.Label(config.algorithms_panel.text, text="Choose an algorithm:", font='Helvetica 20 bold')
menu_label.pack(anchor='center', pady=20)
config.algo_var = tk.StringVar()
config.algo_var.set("choose") # Set default value
config.algo_var.trace('w', update_shape_options)
algos = ["choose", "Perimeter", "Area", "Convex-hull", "Triangulation"]
menu = tk.OptionMenu(config.algorithms_panel.text, config.algo_var, *algos)
menu.pack(anchor='center', pady=10)
choice_label = tk.Label(config.algorithms_panel.text, text="Choose Shape:", font='Helvetica 20 bold')
choice_label.pack(anchor='center', pady=20)
config.poly_var = tk.StringVar()
config.poly_var.set("choose") # Set default value
labels=["choose"]
for shape in config.shapes:
labels.append(shape.get_label())
config.menu = None
l = tk.OptionMenu(config.algorithms_panel.text, config.poly_var, *labels)
l.pack(anchor='center', pady=10)
config.menu = l
calculate_button = tk.Button(config.algorithms_panel.text, text="Calculate", command=activate, font='Helvetica 15 bold')
calculate_button.pack(anchor='center', pady=60)
reset_butto = tk.Button (config.algorithms_panel.text, text="reset", command=reset_button,
font='Helvetica 10')
reset_butto.pack(anchor='center', pady=5)
left_line = tk.Frame(config.algorithms_panel, bg="black", width=2)
left_line.place(x=0, y=0, relheight=1)
right_line = tk.Frame(config.algorithms_panel, bg="black", width=2)
right_line.place(relx=1, y=0, relheight=1, anchor=tk.NE)
else:
config.algorithms_panel.pack_forget()
config.bool_panel_algo = False
def update_shape_options(*args):
selected_algo = config.algo_var.get()
labels = []
if selected_algo == "Convex-hull" or selected_algo == "Triangulation":
for shape in config.shapes:
if isinstance(shape, Polygon):
labels.append(shape.get_label())
else:
for shape in config.shapes:
labels.append(shape.get_label())
config.menu['menu'].delete(0, 'end')
# config.menu = tk.OptionMenu(config.algorithms_panel.text, config.algo_var, *labels)
for option in labels:
config.menu["menu"].add_command(label=option, command=lambda opt=option: config.poly_var.set(opt))
def shape_clicked(x, y):
if x is None or y is None:
return
threshold = 0.5
for shape in config.shapes:
if isinstance(shape, Point):
try:
if np.abs(x - shape.get_x()) <= threshold and np.abs(y - shape.get_y()) <= threshold:
return shape
except TypeError:
pass
elif isinstance(shape, Circle):
center = shape.get_center()
distance = np.sqrt((x - center.get_x()) ** 2 + (y - center.get_y()) ** 2)
if np.abs(distance - shape.radius) <= threshold:
return shape
elif isinstance(shape, Line):
m, b = shape.m_b()
if m==None:
line_y=b
elif b==None:
line_y = m
else:
line_y = m * x + b
if np.abs(y - line_y) <= threshold:
return shape
elif isinstance(shape, Segment):
# start = shape.get_start()
# end = shape.get_end()
# if start.get_x() < end.get_x():
# if x>end.get_x() or x<start.get_x():
# return None
# elif start.get_x() > end.get_x():
# if x<end.get_x() or x>start.get_x():
# return None
m, b = shape.m_b()
if m == None:
segment_y = b
elif b == None:
segment_y = m
else:
segment_y = m * x + b
if np.abs(y - segment_y) <= threshold:
return shape
return
def open_insert_window(point):
# Create a new Tkinter window
insert_window = tk.Toplevel()
config.set_shape = 1
insert_window.geometry("200x120")
insert_window.resizable(False, False)
# Create labels and entry fields for x and y coordinates
x_label = tk.Label(insert_window, text="X Coordinate:")
x_label.pack()
x_entry = tk.Entry(insert_window)
x_entry.pack()
y_label = tk.Label(insert_window, text="Y Coordinate:")
y_label.pack()
y_entry = tk.Entry(insert_window)
y_entry.pack()
# Function to handle the submission of x and y coordinates
def set_point():
x = x_entry.get()
y = y_entry.get()
point.set_p(int(x), int(y))
config.set_shape = 0
insert_window.destroy()
update_label()
update_display()
# Bind the window closing event to a function
def on_closing():
config.set_shape = 0
insert_window.destroy()
# Set the window closing event handler
insert_window.protocol("WM_DELETE_WINDOW", on_closing)
submit_button = tk.Button(insert_window, text="Submit", command=set_point)
submit_button.pack()
def find_widget_by_shape(shape):
for widget in config.label_widgets:
equality = widget.cget("text")
pattern = r'\((.*?)\)'
matches = re.findall(pattern, equality)
label = matches[0]
if label == shape.get_label():
return widget
def on_key(event):
if event.key == 'ctrl+z' or event.key == 'ctrl+Z':
undo()
elif event.key == 'ctrl+y' or event.key == 'ctrl+Y':
redo()
elif event.key == 'delete':
delete_by_label(config.last_shape.get_label())
def on_press(event):
if event.button == 1: # Left mouse button
config.selected_shape = shape_clicked(event.xdata, event.ydata)
if config.selected_shape is not None:
config.start_drag_x, config.start_drag_y = event.xdata, event.ydata
if config.last_shape not in config.shapes:
config.last_shape=None
if config.last_shape is not None:
w = find_widget_by_shape(config.last_shape)
if w is not None:
w.configure(fg='black')
update_display()
curr_widget = None
for widget in config.label_widgets:
equality = widget.cget("text")
pattern = r'\((.*?)\)'
matches = re.findall(pattern, equality)
label = matches[0]
if label==config.selected_shape.get_label():
curr_widget = widget
config.selected_shape.set_color('cyan')
curr_widget.configure(fg='cyan')
config.last_widget = curr_widget
config.last_shape = config.selected_shape
plt.draw()
else:
if config.last_shape is not None:
w = find_widget_by_shape(config.last_shape)
if w is not None:
w.configure(fg='black')
update_display()
elif event.button == 3:
config.selected_shape = shape_clicked(event.xdata, event.ydata)
if isinstance(config.selected_shape, Point):
config.start_drag_x, config.start_drag_y = event.xdata, event.ydata
if config.set_shape == 0:
open_insert_window(config.selected_shape)
def on_release(event):
if config.selected_shape is not None:
config.selected_shape = None
config.start_drag_x, config.start_drag_y = None, None
# if config.last_shape is not None and config.last_widget is not None:
# config.last_shape.set_color('cyan')
# w = find_widget_by_shape(config.last_shape)
# if w is not None:
#
# w.configure(fg='cyan')
def on_motion(event):
if config.selected_shape is not None and event.xdata is not None and event.ydata is not None and event.button == 1:
x, y = event.xdata, event.ydata
dx = x - config.start_drag_x
dy = y - config.start_drag_y
config.start_drag_x, config.start_drag_y = x, y
if isinstance(config.selected_shape, Point):
s = config.selected_shape
s.set_x(dx)
s.set_y(dy)
elif isinstance(config.selected_shape, Circle):
center = config.selected_shape.get_center()
center.set_x(dx)
center.set_y(dy)
elif isinstance(config.selected_shape, Line): # Check if the selected_shape is a Line
s = config.selected_shape
s.set_start_point(dx, dy)
s.set_end_point(dx, dy)
elif isinstance(config.selected_shape, Segment): # Check if the selected_shape is a Line
s = config.selected_shape
s.set_start_point(dx, dy)
s.set_end_point(dx, dy)
update_display()
update_label()
plt.draw()
def shape_set_coordinate(shape, x_coord, y_coord):
dx = x_coord
dy = y_coord
if isinstance(shape, Point):
shape.coords[0][0] += dx
shape.coords[0][1] += dy
shape.set_x(dx)
shape.set_y(dy)
elif isinstance(shape, Circle):
shape.get_center().coords[0][0] += dx
shape.get_center().coords[0][1] += dy
shape.set_center(dx, dy)
elif isinstance(shape, Line):
start = shape.get_start()
end = shape.get_end()
start.coords[0][0] += dx
start.coords[0][1] += dy
shape.set_start_point(dx, dy)
end.coords[0][0] += dx
end.coords[0][1] += dy
shape.set_end_point(dx, dy)
elif isinstance(shape, Segment):
start = shape.get_start()
end = shape.get_end()
start.coords[0][0] += dx
start.coords[0][1] += dy
shape.set_start_point(dx, dy)
end.coords[0][0] += dx
end.coords[0][1] += dy
shape.set_end_point(dx, dy)
update_display()
update_label()
plt.draw()
def on_scroll(event):
ax = config.ax
fig = config.fig
x, y = event.xdata, event.ydata
if event.button == 'up': # Zoom in
factor = 0.95
if ax.get_xlim()[1] - ax.get_xlim()[0] < 10: # Check if x range is too small
return
if ax.get_ylim()[1] - ax.get_ylim()[0] < 10: # Check if y range is too small
return
elif event.button == 'down': # Zoom out
factor = 1.05
# Check if x range or y range is too large
x_range = ax.get_xlim()[1] - ax.get_xlim()[0]
y_range = ax.get_ylim()[1] - ax.get_ylim()[0]
if x_range > 100 or y_range > 100:
return
# Check if x range or y range is too small
if x_range < 1 or y_range < 1:
return
elif event.button == 'pan': # Drag
# Calculate the distance moved
dx = event.x - event.lastx
dy = event.y - event.lasty
# Update the plot limits based on the distance moved
x_lim = ax.get_xlim()
y_lim = ax.get_ylim()
ax.set_xlim(x_lim[0] - dx, x_lim[1] - dx)
ax.set_ylim(y_lim[0] - dy, y_lim[1] - dy)
# Redraw the plot
fig.canvas.draw_idle()
return
x_lim = ax.get_xlim()
y_lim = ax.get_ylim()
ax.set_xlim(x - factor * (x - x_lim[0]), x + factor * (x_lim[1] - x))
ax.set_ylim(y - factor * (y - y_lim[0]), y + factor * (y_lim[1] - y))
x_ticks_major = range(int(ax.get_xlim()[0]), int(ax.get_xlim()[1]) + 1, 1)
y_ticks_major = range(int(ax.get_ylim()[0]), int(ax.get_ylim()[1]) + 1, 1)
ax.xaxis.set_ticks(x_ticks_major, minor=False)
ax.yaxis.set_ticks(y_ticks_major, minor=False)
# Set grid lines
ax.grid(True, which='major', linewidth=1)
ax.grid(True, which='minor', linewidth=0.5)
fig.canvas.draw_idle()
def set_shape_color(event):
update_display()
clicked_label = event.widget
if config.last_shape is not None and config.last_widget is not None:
w = find_widget_by_shape(config.last_shape)
if w is not None:
w.configure(fg='black')
equality = clicked_label.cget("text")
pattern = r'\((.*?)\)'
matches = re.findall(pattern, equality)
label = matches[0]
shape = get_shape_by_label(label)
shape.set_color('cyan')
clicked_label.configure(fg='cyan')
config.last_widget = clicked_label
config.last_shape = shape
plt.draw()
def hide(event):
clicked_label = event.widget
equality = clicked_label.cget("text")
# label = re.match("\((\\w+)\)", equality).groups()[0]
pattern = r'\((.*?)\)'
matches = re.findall(pattern, equality)
label = matches[0]
shape = get_shape_by_label(label)
if isinstance(shape, Point):
if shape.is_hidden():
shape.set_hidden(False)
else:
shape.set_hidden(True)
# circle = shape.is_circle_part()
# line = shape.is_line_part()
# segment = shape.is_segment_part()
# if circle:
# if shape.is_hidden():
# circle.set_hidden(False)
# shape.set_hidden(False)
#
# else:
# circle.set_hidden(True)
# shape.set_hidden(True)
#
# if line:
# if shape.is_hidden():
# line.get_start().set_hidden(False)
# line.get_end().set_hidden(False)
# line.set_hidden(False)
#
# else:
# line.get_start().set_hidden(True)
# line.get_end().set_hidden(True)
# line.set_hidden(True)
#
# if segment:
# if shape.is_hidden():
# segment.get_start().set_hidden(False)
# segment.get_end().set_hidden(False)
# segment.set_hidden(False)
#
# else:
# segment.get_start().set_hidden(True)
# segment.get_end().set_hidden(True)
# segment.set_hidden(True)
#
# elif not line and not circle and not segment:
# if shape.is_hidden():
# shape.set_hidden(False)
# else:
# shape.set_hidden(True)
if isinstance(shape, Line):
if shape.is_hidden():
shape.get_start().set_hidden(False)
shape.get_end().set_hidden(False)
shape.set_hidden(False)
else:
shape.get_start().set_hidden(True)
shape.get_end().set_hidden(True)
shape.set_hidden(True)
if isinstance(shape, Segment):
if shape.is_hidden():
shape.get_start().set_hidden(False)
shape.get_end().set_hidden(False)
shape.set_hidden(False)
else:
shape.get_start().set_hidden(True)
shape.get_end().set_hidden(True)
shape.set_hidden(True)
if isinstance(shape, Circle):
if shape.is_hidden():
shape.get_center().set_hidden(False)
shape.set_hidden(False)
else:
shape.get_center().set_hidden(True)
shape.set_hidden(True)
update_display()
update_label()
def reset_cids():
if not config.cid:
config.ax.figure.canvas.mpl_disconnect(config.cid)
if not config.circle_cid: