/
tk.py
851 lines (700 loc) · 31.3 KB
/
tk.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
# MIT License, copyright Ewan Macpherson, 2016; see LICENCE in root directory
# Tk graphical user interface for easement curve calculations
from abc import ABCMeta, abstractmethod
import json
import os.path
import sys
import tkinter as tk
import tkinter.font as tkfont
import tkinter.ttk as ttk
from ec import base_path, coord, section, curve
# TODO: Add gettext support. Next version
# TODO: Consider adding speed tolerance profiles. Next version
def resource_path(relative_path):
""" Get absolute path to resource from project root directory, works for
dev and for PyInstaller
"""
# stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
abs_path = sys._MEIPASS
except AttributeError:
# Assume that root directory is one above the module directory this
# script resides in
abs_path = base_path
return os.path.join(abs_path, relative_path)
def text_length(length, font='TkDefaultFont'):
""" Retrieves the length of a string defined by number of characters
in pixels.
"""
base_length = tkfont.nametofont(font).measure('e' * 80)
return round(base_length * length / 80)
class InterfaceException(Exception):
pass
class MainWindow(ttk.Frame):
""" Main application window. """
default_settings = {
'speed units': 'mph',
'decimal places': 1,
'split static curve': False,
'results rows': 5
}
validate_settings = {
'speed units': {'mph', 'km/h'},
'decimal places': {1, 2, 3},
'split static curve': {True, False},
'results rows': set(range(1, 25))
}
file = 'ec_settings.json'
def __init__(self, parent, **kwargs):
super(MainWindow, self).__init__(parent, **kwargs)
self.config(padding='{t} {t} {t} {t}'.format(t=text_length(1)))
self.grid(row=0, column=0)
self.parent = parent
self.settings, self.setdialog, self.message = (None,) * 3
self.exists = True
self.load_settings()
self._kph = None
self._method = tk.StringVar()
self.current_entry, self.description, self.msg, self.sr, \
self.entries, self.minimum_radius, self.result = (None,) * 7
self.body()
self.parent.bind('<Return>', self.calculate)
@property
def method(self):
""" Retrieves method selection. """
return self._method.get()
@method.setter
def method(self):
raise AttributeError('method property cannot be set manually.')
@property
def mph(self):
""" Speed tolerance in mph. """
return self._kph / 1.609344
@mph.setter
def mph(self, value):
self._kph = value * 1.609344
@property
def kph(self):
""" Speed tolerance in kph. """
return self._kph
@kph.setter
def kph(self, value):
self._kph = value
def body(self):
self.columnconfigure(2, weight=1)
self.columnconfigure(4, pad=text_length(1))
self.rowconfigure(3, pad=text_length(1))
self.rowconfigure(4, pad=text_length(1))
options = ['1', '2']
ttk.Label(self, text='Select method ').grid(row=0, column=0)
ttk.OptionMenu(self, self._method, options[0], *options,
command=self.refresh_method).grid(row=0, column=1)
ttk.Button(self, text='Settings', command=self.open_settings_dialog
).grid(row=0, column=4, sticky=(tk.N, tk.E))
self.description = MethodDescription(self)
self.description.grid(row=1, column=0, columnspan=5,
sticky=(tk.W, tk.E))
self.sr = SpeedRadius(self)
self.sr.grid(row=2, column=0, columnspan=5, sticky=(tk.W, tk.E))
self.entries = {'1': EntryMethod1(self, row=3),
'2': EntryMethod2(self, row=3)}
self.current_entry = self.entries[self.method]
# Hiding all widgets not selected
for k in [i for i in self.entries.keys() if i != self.method]:
self.entries[k].grid_remove()
ttk.Style().configure('Red.TLabel', foreground="red")
if self.message is None:
self.message = 'All OK.'
self.msg = ttk.Label(self, text=self.message)
self.msg.config(width=56, wraplength=text_length(56))
self.msg.grid(row=4, column=0, columnspan=3, sticky=tk.W)
ttk.Button(self, text='Calculate', command=self.calculate
).grid(row=4, column=3, sticky=(tk.N, tk.E))
ttk.Button(self, text='Clear', command=self.clear
).grid(row=4, column=4, sticky=(tk.N, tk.E))
self.result = Result(self)
self.result.grid(row=5, column=0, columnspan=5)
def load_settings(self):
""" Loads settings from a JSON file. If no setttings are found, will
use predefined settings instead.
"""
try:
with open(self.file, 'r') as jf:
settings = json.load(jf)
except FileNotFoundError:
settings = self.default_settings
self.exists = False
self.message = ("Settings file not found. The default options "
"have been selected.")
except (FileExistsError, PermissionError):
settings = self.default_settings
self.exists = False
self.message = ("Another file or directory has the name '{}'. The "
"default options have been selected."
"".format(self.file))
except json.JSONDecodeError:
settings = self.default_settings
self.message = ("The settings file cannot be loaded. The default "
"options have been selected.")
if settings.keys() != self.default_settings.keys():
self.settings = self.default_settings
self.message = ("The settings file has the wrong keys. Try "
"resaving the file. The default options have been "
"selected.")
else:
if all(settings[i] in self.validate_settings[i] for i in
settings.keys()):
# Can import settings
self.settings = settings
else:
self.settings = self.default_settings
self.message = ("The settings file has the wrong values. Try "
"resaving the file. The default options have "
"been selected.")
def save_settings(self):
""" Saves settings to a JSON file. If the settings are the same no
action is taken. If there are problems errors will be raised.
"""
try:
with open(self.file, 'r') as jf:
old_settings = json.load(jf)
if old_settings == self.settings:
# Settings same; no need to save
return
except FileNotFoundError:
# We still want to save it anyway
pass
# Else:
with open(self.file, 'w') as jf:
json.dump(self.settings, jf, indent=2, sort_keys=True)
def open_settings_dialog(self, event=None):
""" Opens the Settings dialog. If it has already been initialised the
dialog is deiconified.
"""
try:
self.setdialog.show()
except AttributeError:
self.setdialog = SettingsDialog(self, self.parent)
def refresh_method(self, event=None):
""" Command to refresh method description and data entries depending
on which method was selected.
"""
# Method description changed
self.description.refresh()
# Hides current entry widget and shows new one
self.current_entry.grid_remove()
self.current_entry = self.entries[self.method]
self.current_entry.grid_replace()
# Lowers entry widget below message/actions to ensure correct tab order
self.current_entry.lift(self.sr)
def refresh_message(self, message, colour='black'):
""" Command to refresh the calculation message. """
if colour == 'red':
self.msg.config(text=message, style='Red.TLabel')
else:
self.msg.config(text=message, style='TLabel')
def clear(self):
""" Command to clear and reset all entries/selections in data entry.
"""
self.current_entry.reset_values()
def calculate(self, event=None):
""" Takes data, calculates the curve geometry and passes results to
table.
"""
self.result.clear_table()
try:
if self.sr.dim.get() == 'mph':
self.mph = float(self.sr.speed.get())
else:
self.kph = float(self.sr.speed.get())
self.minimum_radius = float(self.sr.minimum.get())
except ValueError:
self.refresh_message('Error: Speed tolerance and minimum radius '
'must be valid numbers.', 'red')
return
try:
result = self.current_entry.get_result()
except AttributeError:
self.refresh_message('Error: All fields must be filled in.', 'red')
raise
except (InterfaceException, coord.CoordError, section.TrackError,
curve.CurveError) as err:
err_string = {InterfaceException: 'Input error: ',
coord.CoordError: 'Coordinate error: ',
section.TrackError: 'Track section error: ',
curve.CurveError: 'Curve calculation error: '}
self.refresh_message(err_string[type(err)] + str(err), 'red')
return
else:
self.refresh_message('All OK.')
self.result.load_table(self.display_data(result))
def display_data(self, result):
""" Formats the results data to make them readable and gives correct
decimal places.
"""
data = []
# Check if there are more than one section of a type
count_static = sum(1 for ts in result if ts.org_type == 'static')
count_ease = sum(1 for ts in result if ts.org_type == 'easement')
s, e = 0, 0
decimal_places = self.settings.get('decimal places', 1)
for i, ts in enumerate(result):
# Creating the radius of curvature text
if ts.org_curvature == ts.curvature or ts.org_curvature is None:
# Only one value needed.
if ts.curvature == 0:
roc_text = ts.clockwise.capitalize()
else:
roc_text = '{roc:.{dp}f} {cw}' \
''.format(roc=ts.radius, cw=ts.clockwise,
dp=decimal_places)
else:
# Both values needed.
if ts.org_curvature != 0 and ts.curvature != 0:
roc_text = '{st:.{dp}f} to {end:.{dp}f} {cw}' \
''.format(st=ts.org_radius, end=ts.radius,
cw=ts.clockwise, dp=decimal_places)
elif ts.org_curvature == 0 and ts.curvature != 0:
roc_text = '{st} to {end:.{dp}f} {cw}' \
''.format(st=ts.org_clockwise.capitalize(),
end=ts.radius, cw=ts.clockwise,
dp=decimal_places)
elif ts.org_curvature != 0 and ts.curvature == 0:
roc_text = '{st:.{dp}f} {cw} to {end}' \
''.format(st=ts.org_radius, cw=ts.org_clockwise,
end=ts.clockwise.lower(),
dp=decimal_places)
else:
raise ValueError(
'Something went wrong here - org curvature {0} and '
'curvature {1}'.format(ts.org_curvature, ts.curvature))
# Setting curve names
if i == 0 and ts.org_type is None:
section_name = 'Start point'
elif ts.org_type == 'static':
if count_static > 1:
s += 1
section_name = 'Static {}'.format(s)
else:
section_name = 'Static'
elif ts.org_type == 'easement':
if count_ease > 1:
e += 1
section_name = 'Easement {}'.format(e)
else:
section_name = 'Easement'
else:
raise AttributeError('Incorrect type {!r} for TrackCoord '
'object {!r}.'.format(ts.org_type, ts))
# Setting length value to 1 decimal place
if ts.org_length is not None:
length = '{:.{dp}f}'.format(ts.org_length, dp=decimal_places)
else:
length = ''
# Setting position values to 3 decimal places
pos_x, pos_z = '{:.3f}'.format(ts.pos_x), \
'{:.3f}'.format(ts.pos_z)
# Setting rotation and quad values to 3 decimal places
rotation, quad = '{:.3f}'.format(ts.quad[0]), ts.quad[1]
if rotation in ['0.000', '360.000']:
rotation = '0.000'
quad = 'N' if quad in ['NE', 'NW'] else 'S'
elif rotation == '90.000':
quad = 'W' if quad in ['NW', 'SW'] else 'E'
data.append((section_name, length, roc_text,
pos_x, pos_z, rotation, quad))
return data
class SettingsDialog(tk.Toplevel):
""" Extra dialog for editing settings. """
def __init__(self, parent, root):
super(SettingsDialog, self).__init__(root)
self.root, self.parent = root, parent
# Setting up the window, should be transient (ie not full window)
self.title('Settings')
self.transient(parent)
self.resizable(False, False)
self.iconbitmap(resource_path('resources/logo.ico'))
self.move() # Moving window relative to parent window
self.focus_set() # Switching focus to this window
self.temp_settings = {
'speed units': tk.StringVar(),
'results rows': tk.IntVar(),
'decimal places': tk.IntVar(),
'split static curve': tk.BooleanVar()
}
self.message, self.msg = None, None
# The window body
self.container = ttk.Frame(
self, padding='{t} {t} {t} {t}'.format(t=text_length(1)))
self.container.grid(row=0, column=0)
self.load_settings()
self.body()
# What happens when you do something
self.protocol('WM_DELETE_WINDOW', self.cancel)
self.bind('<Escape>', self.cancel)
self.bind('<Return>', self.cancel)
def load_settings(self):
""" Loads settings from parent window. """
for k, v in self.temp_settings.items():
v.set(self.parent.settings.get(k, self.parent.default_settings[k]))
def body(self):
""" Main body. """
self.container.columnconfigure(2, pad=text_length(1))
for i in range(6):
self.container.rowconfigure(i, pad=text_length(1))
# Speed units
ttk.Label(self.container, text='Speed tolerance units at startup'
).grid(row=0, column=0, columnspan=2, sticky=tk.W)
speed_options = ['mph', 'km/h']
units = ttk.Combobox(self.container, width=6,
textvariable=self.temp_settings['speed units'])
units.config(values=speed_options, state='readonly')
units.grid(row=0, column=2)
# Results rows
ttk.Label(self.container, text='Number of rows in results table'
).grid(row=1, column=0, columnspan=2, sticky=tk.W)
results_options = list(range(5, 16))
rows = ttk.Combobox(self.container, width=6,
textvariable=self.temp_settings['results rows'])
rows.config(values=results_options, state='readonly')
rows.grid(row=1, column=2)
# Decimal places
ttk.Label(self.container, text='Decimal places for length and RoC'
).grid(row=2, column=0, columnspan=2, sticky=tk.W)
decimal_options = list(range(1, 4))
rows = ttk.Combobox(self.container, width=6,
textvariable=self.temp_settings['decimal places'])
rows.config(values=decimal_options, state='readonly')
rows.grid(row=2, column=2)
# Split up static curves
split = ttk.Checkbutton(self.container,
text='Split static curves into 500 m sections')
split.config(variable=self.temp_settings['split static curve'])
split.grid(row=3, column=0, columnspan=3, sticky=tk.W)
# Message section
ttk.Style().configure('Red.TLabel', foreground='red')
self.message = ttk.Label(self.container, text='')
self.message.grid(row=4, column=0, columnspan=3, sticky=tk.W)
if not self.parent.exists:
self.refresh_message('New file {} will be created'
''.format(self.parent.file))
# Save button
ttk.Button(self.container, text='Save', command=self.save
).grid(row=5, column=1, sticky=tk.E)
# Close button
ttk.Button(self.container, text='Cancel', command=self.cancel
).grid(row=5, column=2, sticky=tk.E)
def refresh_message(self, message, colour='black'):
""" Changes text at bottom to new message - if 'colour' is 'red' the
it will also change colour.
"""
try:
if colour == 'red':
self.message.config(text=message, style='Red.TLabel')
else:
self.message.config(text=message, style='TLabel')
except AttributeError as err:
raise AttributeError('function refresh_message raised before '
'message widget was created') from err
def save(self, event=None):
""" Save command: rewrites settings and save to JSON file. """
# Saves new values to parent's setting attribute
for k, v in self.temp_settings.items():
self.parent.settings[k] = v.get()
# Sets results table to new value of rows.
self.parent.result.refresh_rows(
self.parent.settings.get('results rows', 5))
try:
self.parent.save_settings()
except PermissionError:
message = 'Error: cannot save file {}'.format(self.parent.file)
self.refresh_message(message, 'red')
return
# Closes window
self.withdraw()
def move(self, offset=30):
""" Moves this window to position relative to parent window. """
x, y = self.root.winfo_rootx(), self.root.winfo_rooty()
self.geometry('+{x:d}+{y:d}'.format(x=x+offset, y=y+offset))
def cancel(self, event=None):
""" Restores settings to original and closes window. """
# Restores original settings
self.load_settings()
self.withdraw()
def show(self, event=None):
""" Used by parent window to reopen the dialog. """
self.move()
self.deiconify()
class MethodDescription(ttk.LabelFrame):
""" LabelFrame widget for displaying method description. """
description = {
'1': ("Takes two straight tracks at different angles, and creates an "
"easement curve with set radius of curvature connecting the two "
"tracks.\n"
"Direction (optional) - forces curve to be aligned in that "
"direction even if it is longer."),
'2': ("Extends an easement curve onwards from a track to join with "
"another straight track.\n"
"Additional coordinates (optional) - used to define radius of "
"curvature at the start of curve.")
}
def __init__(self, parent):
super(MethodDescription, self).__init__(parent)
self.parent = parent
self.config(padding="0 0 0 4",
text='Method {} description'.format(self.parent.method))
self.grid(sticky=(tk.W, tk.E))
self.text = None
self.body()
def body(self):
self.text = ttk.Label(self, text=self.description[self.parent.method])
self.text.config(
width=80, wraplength=int(text_length(80)), padding="4 0 0 4")
self.text.grid(sticky=(tk.W, tk.E))
def refresh(self):
""" Refreshes the heading and text when method selection changes. """
self.config(text='Method {} description'.format(self.parent.method))
self.text.config(text=self.description[self.parent.method])
class SpeedRadius(ttk.LabelFrame):
""" LabelFrame widget for setting speed tolerance and minimum radius of
curvature.
"""
def __init__(self, parent):
super(SpeedRadius, self).__init__(parent)
self.config(padding="4 0 0 8", text='Curve setup')
self.grid(sticky=(tk.W, tk.E))
self.columnconfigure(1, pad=4)
self.parent = parent
self.speed = tk.StringVar()
self.dim = tk.StringVar()
self.minimum = tk.StringVar()
self.body()
def body(self):
ttk.Label(self, text='Speed tolerance ', width=16
).grid(row=0, column=0, sticky=tk.W)
ttk.Entry(self, textvariable=self.speed, width=8
).grid(row=0, column=1, sticky=tk.W)
options = ['mph', 'km/h']
dimensions = ttk.Combobox(self, textvariable=self.dim)
dimensions.config(width=6, values=options, state='readonly')
dimensions.set(self.parent.settings.get('speed units', 'mph'))
dimensions.grid(row=0, column=2, sticky=tk.W)
ttk.Label(self, text='Minimum radius of curvature ', padding="8 0 0 0"
).grid(row=0, column=3, columnspan=2, sticky=tk.W)
ttk.Entry(self, textvariable=self.minimum, width=8
).grid(row=0, column=5, sticky=tk.W)
ttk.Label(self, text='m', padding="4 0 0 0"
).grid(row=0, column=6, sticky=tk.W)
class BaseEntryM(ttk.LabelFrame, metaclass=ABCMeta):
""" Common class for entry data table. Must be subclassed. """
quads = ['NE', 'SE', 'SW', 'NW']
def __init__(self, parent, row):
super(BaseEntryM, self).__init__(parent)
self.config(text='Curve data', padding="0 0 0 10")
self.row = row
self.grid_replace()
# Data entries
self.line0 = self.coord_stringvar()
self.line1 = self.coord_stringvar()
self.line2 = self.coord_stringvar()
self.radius, self.direction = tk.StringVar(), tk.StringVar()
# All rows and columns in grid
for i in range(5):
self.grid_columnconfigure(i, pad=4)
for j in range(4):
self.grid_rowconfigure(j, pad=4)
self.parent = parent
self.get_table()
def grid_replace(self):
""" Restores this frame to original position. """
self.grid(row=self.row, column=0, columnspan=5,
sticky=(tk.N, tk.W, tk.E))
def args(self):
""" Dict to be used as arguement for the TrackCurve instances. """
return {'speed': self.parent.kph,
'minimum': self.parent.minimum_radius,
'split': self.parent.settings.get('split static curve', False)}
def reset_values(self):
""" Resets all entries to their original configuration. """
self.radius.set('')
self.direction.set('N/A')
for line in [self.line0, self.line1, self.line2]:
for entry in line.values():
entry.set('')
self.line0['r'].set('0')
self.line0['q'].set('NE')
@staticmethod
def coord_stringvar():
return {j: tk.StringVar() for j in 'xzrq'}
@staticmethod
def get_coord(data):
""" Takes a list with 2 or 4 variables - X and Z positions, rotation
and quad - and converts to a TrackCoord object.
"""
coordinates = {k: v.get() for k, v in data.items()}
try:
if coordinates['q'].upper() in ['NE', 'SE', 'SW', 'NW']:
rotation = float(coordinates['r'])
quad = coord.Q[coordinates['q'].upper()]
else:
raise AttributeError
dict_coord = {
'pos_x': float(coordinates['x']),
'pos_z': float(coordinates['z']),
'rotation': rotation,
'quad': quad,
'curvature': 0
}
except (AttributeError, ValueError):
raise InterfaceException('The coordinates must be valid integers/'
'floats with a quadrant specified.')
return coord.TrackCoord(**dict_coord)
@abstractmethod
def get_table(self):
""" Creates grid of entries and labels. """
pass
@abstractmethod
def get_result(self):
""" Takes entries and calculates the result. """
pass
def header(self, text, row=0, column=0):
ttk.Label(self, text=text).grid(row=row, column=column, sticky=tk.W)
def start_label(self, text, row, column=0):
ttk.Label(self, text=text, width=24
).grid(row=row, column=column, sticky=tk.E)
def coord_entry(self, variable, row, column):
entry = ttk.Entry(self, textvariable=variable, width=10)
entry.grid(row=row, column=column, sticky=tk.W)
def coord_menu(self, variable, options, row, column, default=False):
menu = ttk.Combobox(self, textvariable=variable)
menu.config(width=8, values=options, state='readonly')
menu.grid(row=row, column=column, sticky=tk.W)
if default:
# Sets first item in options list as default value
menu.current(0)
class EntryMethod1(BaseEntryM):
""" Fits curve with set radius of curvature to a pair of straight tracks
at an angle. Can set CW/ACW for direction the curve takes.
"""
def get_table(self):
self.header('Position X', column=1)
self.header('Position Z', column=2)
self.header('Rotation Y', column=3)
self.header('Quadrant', column=4)
self.start_label('First straight track', 1)
self.coord_entry(self.line1['x'], 1, 1)
self.coord_entry(self.line1['z'], 1, 2)
self.coord_entry(self.line1['r'], 1, 3)
self.coord_menu(self.line1['q'], self.quads, 1, 4)
self.start_label('Second straight track', 2)
self.coord_entry(self.line2['x'], 2, 1)
self.coord_entry(self.line2['z'], 2, 2)
self.coord_entry(self.line2['r'], 2, 3)
self.coord_menu(self.line2['q'], self.quads, 2, 4)
self.start_label('Radius of curvature', 3)
self.coord_entry(self.radius, 3, 1)
ttk.Label(self, text='m').grid(row=3, column=2, sticky=tk.W)
ttk.Label(self, text='direction', justify=tk.RIGHT,
padding="0 0 4 0").grid(row=3, column=3, sticky=tk.E)
self.coord_menu(self.direction, ['N/A', 'CW', 'ACW'], 3, 4,
default=True)
def get_result(self):
start_track = self.get_coord(self.line1)
end_track = self.get_coord(self.line2)
try:
curve_radius = float(self.radius.get())
except ValueError:
raise InterfaceException('Radius of curvature must be a number.')
track = curve.TrackCurve(curve=start_track, **self.args())
clockwise = {'CW': True, 'ACW': False}.get(self.direction.get())
return track.curve_fit_radius(other=end_track, radius=curve_radius,
clockwise=clockwise)
class EntryMethod2(BaseEntryM):
""" Extends curve from point on track (can be either straight or curved -
radius of curvature is calculated from additional pair of coordinates)
to join a straight track.
"""
def get_table(self):
self.header('Position X', column=1)
self.header('Position Z', column=2)
self.header('Rotation Y', column=3)
self.header('Quadrant', column=4)
self.start_label('Starting point on track', 1)
self.coord_entry(self.line1['x'], 1, 1)
self.coord_entry(self.line1['z'], 1, 2)
self.coord_entry(self.line1['r'], 1, 3)
self.coord_menu(self.line1['q'], self.quads, 1, 4)
self.start_label('Additional coordinates', 2)
self.coord_entry(self.line0['x'], 2, 1)
self.coord_entry(self.line0['z'], 2, 2)
self.line0['r'].set('0')
self.line0['q'].set('NE')
self.start_label('Straight track to join', 3)
self.coord_entry(self.line2['x'], 3, 1)
self.coord_entry(self.line2['z'], 3, 2)
self.coord_entry(self.line2['r'], 3, 3)
self.coord_menu(self.line2['q'], self.quads, 3, 4)
def get_result(self):
start_track = self.get_coord(self.line1)
end_track = self.get_coord(self.line2)
track = curve.TrackCurve(curve=start_track, **self.args())
# Check if first two fields are empty - if so, track is straight
if all(self.line0[k].get() == '' for k in 'xz'):
return track.curve_fit_point(other=end_track)
else:
pre_track = self.get_coord(self.line0)
return track.curve_fit_point(other=end_track, add_point=pre_track)
class Result(ttk.Frame):
""" Results table, based on TreeView widget. """
# TODO: Consider changing TreeView to a grid of Text widgets.
def __init__(self, parent):
super(Result, self).__init__(parent)
self.grid(sticky=(tk.W, tk.E))
self.treeview = None
self.parent = parent
self.create_table()
def create_table(self):
""" Initalises table. """
rows = self.parent.settings.get('results rows', 5)
tv = ttk.Treeview(self, height=rows)
ttk.Style().configure('Treeview', rowheight=text_length(3.5))
columns = ('section', 'length', 'roc', 'pos_x',
'pos_z', 'rotation', 'quad')
columns_d = {
'section': ('Curve section', 'w', 14),
'length': ('Length', 'e', 9),
'roc': ('Radius of curvature', 'w', 24),
'pos_x': ('Position X', 'e', 11),
'pos_z': ('Position Z', 'e', 11),
'rotation': ('Rotation', 'e', 10),
'quad': ('Quad', 'w', 7)
}
tv['columns'] = columns
# Hides the first column
tv['show'] = 'headings'
for col in columns:
c = columns_d[col]
tv.heading(col, text=c[0], anchor='w')
tv.column(col, anchor=c[1], width=text_length(c[2]))
tv.grid(sticky=(tk.N, tk.S, tk.W, tk.E))
self.treeview = tv
def refresh_rows(self, rows, event=None):
if self.treeview.cget('height') != rows:
self.treeview.config(height=rows)
def load_table(self, data):
""" Loads table using data (list of tuples). """
for sec in data:
self.treeview.insert('', 'end', text='', values=sec)
def clear_table(self):
""" Deletes all data from table. """
self.treeview.delete(*self.treeview.get_children())
def main():
root = tk.Tk()
root.title('Easement curve calculator')
root.resizable(height=False, width=False)
root.iconbitmap(resource_path('resources/logo.ico'))
MainWindow(root)
root.mainloop()
if __name__ == "__main__":
main()