Debian Codegraph @

Lib/turtledemo/__main__.py

raw
1 #!/usr/bin/env python3
2
3 """
4 ----------------------------------------------
5 turtleDemo - Help
6 ----------------------------------------------
7
8 This document has two sections:
9
10 (1) How to use the demo viewer
11 (2) How to add your own demos to the demo repository
12
13
14 (1) How to use the demo viewer.
15
16 Select a demoscript from the example menu.
17 The (syntax colored) source code appears in the left
18 source code window. IT CANNOT BE EDITED, but ONLY VIEWED!
19
20 The demo viewer windows can be resized. The divider between text
21 and canvas can be moved by grabbing it with the mouse. The text font
22 size can be changed from the menu and with Control/Command '-'/'+'.
23 It can also be changed on most systems with Control-mousewheel
24 when the mouse is over the text.
25
26 Press START button to start the demo.
27 Stop execution by pressing the STOP button.
28 Clear screen by pressing the CLEAR button.
29 Restart by pressing the START button again.
30
31 SPECIAL demos, such as clock.py are those which run EVENTDRIVEN.
32
33 Press START button to start the demo.
34
35 - Until the EVENTLOOP is entered everything works
36 as in an ordinary demo script.
37
38 - When the EVENTLOOP is entered, you control the
39 application by using the mouse and/or keys (or it's
40 controlled by some timer events)
41 To stop it you can and must press the STOP button.
42
43 While the EVENTLOOP is running, the examples menu is disabled.
44
45 - Only after having pressed the STOP button, you may
46 restart it or choose another example script.
47
48 * * * * * * * *
49 In some rare situations there may occur interferences/conflicts
50 between events concerning the demo script and those concerning the
51 demo-viewer. (They run in the same process.) Strange behaviour may be
52 the consequence and in the worst case you must close and restart the
53 viewer.
54 * * * * * * * *
55
56
57 (2) How to add your own demos to the demo repository
58
59 - Place the file in the same directory as turtledemo/__main__.py
60 IMPORTANT! When imported, the demo should not modify the system
61 by calling functions in other modules, such as sys, tkinter, or
62 turtle. Global variables should be initialized in main().
63
64 - The code must contain a main() function which will
65 be executed by the viewer (see provided example scripts).
66 It may return a string which will be displayed in the Label below
67 the source code window (when execution has finished.)
68
69 - In order to run mydemo.py by itself, such as during development,
70 add the following at the end of the file:
71
72 if __name__ == '__main__':
73 main()
74 mainloop() # keep window open
75
76 python -m turtledemo.mydemo # will then run it
77
78 - If the demo is EVENT DRIVEN, main must return the string
79 "EVENTLOOP". This informs the demo viewer that the script is
80 still running and must be stopped by the user!
81
82 If an "EVENTLOOP" demo runs by itself, as with clock, which uses
83 ontimer, or minimal_hanoi, which loops by recursion, then the
84 code should catch the turtle.Terminator exception that will be
85 raised when the user presses the STOP button. (Paint is not such
86 a demo; it only acts in response to mouse clicks and movements.)
87 """
88 import sys
89 import os
90
91 from tkinter import *
92 from idlelib.colorizer import ColorDelegator, color_config
93 from idlelib.percolator import Percolator
94 from idlelib.textview import view_text
95 import turtle
96 from turtledemo import __doc__ as about_turtledemo
97
98 if sys.platform == 'win32':
99 from idlelib.util import fix_win_hidpi
100 fix_win_hidpi()
101
102 demo_dir = os.path.dirname(os.path.abspath(__file__))
103 darwin = sys.platform == 'darwin'
104 STARTUP = 1
105 READY = 2
106 RUNNING = 3
107 DONE = 4
108 EVENTDRIVEN = 5
109
110 btnfont = ("Arial", 12, 'bold')
111 txtfont = ['Lucida Console', 10, 'normal']
112
113 MINIMUM_FONT_SIZE = 6
114 MAXIMUM_FONT_SIZE = 100
115 font_sizes = [8, 9, 10, 11, 12, 14, 18, 20, 22, 24, 30]
116
117 def getExampleEntries():
118 return [entry[:-3] for entry in os.listdir(demo_dir) if
119 entry.endswith(".py") and entry[0] != '_']
120
121 help_entries = ( # (help_label, help_doc)
122 ('Turtledemo help', __doc__),
123 ('About turtledemo', about_turtledemo),
124 ('About turtle module', turtle.__doc__),
125 )
126
127
128 class DemoWindow(object):
129
130 def __init__(self, filename=None):
131 self.root = root = turtle._root = Tk()
132 root.title('Python turtle-graphics examples')
133 root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
134
135 if darwin:
136 import subprocess
137 # Make sure we are the currently activated OS X application
138 # so that our menu bar appears.
139 subprocess.run(
140 [
141 'osascript',
142 '-e', 'tell application "System Events"',
143 '-e', 'set frontmost of the first process whose '
144 'unix id is {} to true'.format(os.getpid()),
145 '-e', 'end tell',
146 ],
147 stderr=subprocess.DEVNULL,
148 stdout=subprocess.DEVNULL,)
149
150 root.grid_rowconfigure(0, weight=1)
151 root.grid_columnconfigure(0, weight=1)
152 root.grid_columnconfigure(1, minsize=90, weight=1)
153 root.grid_columnconfigure(2, minsize=90, weight=1)
154 root.grid_columnconfigure(3, minsize=90, weight=1)
155
156 self.mBar = Menu(root, relief=RAISED, borderwidth=2)
157 self.mBar.add_cascade(menu=self.makeLoadDemoMenu(self.mBar),
158 label='Examples', underline=0)
159 self.mBar.add_cascade(menu=self.makeFontMenu(self.mBar),
160 label='Fontsize', underline=0)
161 self.mBar.add_cascade(menu=self.makeHelpMenu(self.mBar),
162 label='Help', underline=0)
163 root['menu'] = self.mBar
164
165 pane = PanedWindow(root, orient=HORIZONTAL, sashwidth=5,
166 sashrelief=SOLID, bg='#ddd')
167 pane.add(self.makeTextFrame(pane))
168 pane.add(self.makeGraphFrame(pane))
169 pane.grid(row=0, columnspan=4, sticky='news')
170
171 self.output_lbl = Label(root, height= 1, text=" --- ", bg="#ddf",
172 font=("Arial", 16, 'normal'), borderwidth=2,
173 relief=RIDGE)
174 if darwin: # Leave Mac button colors alone - #44254.
175 self.start_btn = Button(root, text=" START ", font=btnfont,
176 fg='#00cc22', command=self.startDemo)
177 self.stop_btn = Button(root, text=" STOP ", font=btnfont,
178 fg='#00cc22', command=self.stopIt)
179 self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
180 fg='#00cc22', command = self.clearCanvas)
181 else:
182 self.start_btn = Button(root, text=" START ", font=btnfont,
183 fg="white", disabledforeground = "#fed",
184 command=self.startDemo)
185 self.stop_btn = Button(root, text=" STOP ", font=btnfont,
186 fg="white", disabledforeground = "#fed",
187 command=self.stopIt)
188 self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
189 fg="white", disabledforeground="#fed",
190 command = self.clearCanvas)
191 self.output_lbl.grid(row=1, column=0, sticky='news', padx=(0,5))
192 self.start_btn.grid(row=1, column=1, sticky='ew')
193 self.stop_btn.grid(row=1, column=2, sticky='ew')
194 self.clear_btn.grid(row=1, column=3, sticky='ew')
195
196 Percolator(self.text).insertfilter(ColorDelegator())
197 self.dirty = False
198 self.exitflag = False
199 if filename:
200 self.loadfile(filename)
201 self.configGUI(DISABLED, DISABLED, DISABLED,
202 "Choose example from menu", "black")
203 self.state = STARTUP
204
205
206 def onResize(self, event):
207 cwidth = self.canvas.winfo_width()
208 cheight = self.canvas.winfo_height()
209 self.canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
210 self.canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)
211
212 def makeTextFrame(self, root):
213 self.text_frame = text_frame = Frame(root)
214 self.text = text = Text(text_frame, name='text', padx=5,
215 wrap='none', width=45)
216 color_config(text)
217
218 self.vbar = vbar = Scrollbar(text_frame, name='vbar')
219 vbar['command'] = text.yview
220 vbar.pack(side=RIGHT, fill=Y)
221 self.hbar = hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
222 hbar['command'] = text.xview
223 hbar.pack(side=BOTTOM, fill=X)
224 text['yscrollcommand'] = vbar.set
225 text['xscrollcommand'] = hbar.set
226
227 text['font'] = tuple(txtfont)
228 shortcut = 'Command' if darwin else 'Control'
229 text.bind_all('<%s-minus>' % shortcut, self.decrease_size)
230 text.bind_all('<%s-underscore>' % shortcut, self.decrease_size)
231 text.bind_all('<%s-equal>' % shortcut, self.increase_size)
232 text.bind_all('<%s-plus>' % shortcut, self.increase_size)
233 text.bind('<Control-MouseWheel>', self.update_mousewheel)
234 text.bind('<Control-Button-4>', self.increase_size)
235 text.bind('<Control-Button-5>', self.decrease_size)
236
237 text.pack(side=LEFT, fill=BOTH, expand=1)
238 return text_frame
239
240 def makeGraphFrame(self, root):
241 # t._Screen is a singleton class instantiated or retrieved
242 # by calling Screen. Since tdemo canvas needs a different
243 # configuration, we manually set class attributes before
244 # calling Screen and manually call superclass init after.
245 turtle._Screen._root = root
246
247 self.canvwidth = 1000
248 self.canvheight = 800
249 turtle._Screen._canvas = self.canvas = canvas = turtle.ScrolledCanvas(
250 root, 800, 600, self.canvwidth, self.canvheight)
251 canvas.adjustScrolls()
252 canvas._rootwindow.bind('<Configure>', self.onResize)
253 canvas._canvas['borderwidth'] = 0
254
255 self.screen = screen = turtle.Screen()
256 turtle.TurtleScreen.__init__(screen, canvas)
257 turtle.RawTurtle.screens = [screen]
258 return canvas
259
260 def set_txtsize(self, size):
261 txtfont[1] = size
262 self.text['font'] = tuple(txtfont)
263 self.output_lbl['text'] = 'Font size %d' % size
264
265 def decrease_size(self, dummy=None):
266 self.set_txtsize(max(txtfont[1] - 1, MINIMUM_FONT_SIZE))
267 return 'break'
268
269 def increase_size(self, dummy=None):
270 self.set_txtsize(min(txtfont[1] + 1, MAXIMUM_FONT_SIZE))
271 return 'break'
272
273 def update_mousewheel(self, event):
274 # For wheel up, event.delta = 120 on Windows, -1 on darwin.
275 # X-11 sends Control-Button-4 event instead.
276 if (event.delta < 0) == (not darwin):
277 return self.decrease_size()
278 else:
279 return self.increase_size()
280
281 def configGUI(self, start, stop, clear, txt="", color="blue"):
282 if darwin: # Leave Mac button colors alone - #44254.
283 self.start_btn.config(state=start)
284 self.stop_btn.config(state=stop)
285 self.clear_btn.config(state=clear)
286 else:
287 self.start_btn.config(state=start,
288 bg="#d00" if start == NORMAL else "#fca")
289 self.stop_btn.config(state=stop,
290 bg="#d00" if stop == NORMAL else "#fca")
291 self.clear_btn.config(state=clear,
292 bg="#d00" if clear == NORMAL else "#fca")
293 self.output_lbl.config(text=txt, fg=color)
294
295 def makeLoadDemoMenu(self, master):
296 menu = Menu(master, tearoff=1) # TJR: leave this one.
297
298 for entry in getExampleEntries():
299 def load(entry=entry):
300 self.loadfile(entry)
301 menu.add_command(label=entry, underline=0, command=load)
302 return menu
303
304 def makeFontMenu(self, master):
305 menu = Menu(master, tearoff=0)
306 menu.add_command(label="Decrease", command=self.decrease_size,
307 accelerator=f"{'Command' if darwin else 'Ctrl'}+-")
308 menu.add_command(label="Increase", command=self.increase_size,
309 accelerator=f"{'Command' if darwin else 'Ctrl'}+=")
310 menu.add_separator()
311
312 for size in font_sizes:
313 def resize(size=size):
314 self.set_txtsize(size)
315 menu.add_command(label=str(size), underline=0, command=resize)
316 return menu
317
318 def makeHelpMenu(self, master):
319 menu = Menu(master, tearoff=0)
320
321 for help_label, help_file in help_entries:
322 def show(help_label=help_label, help_file=help_file):
323 view_text(self.root, help_label, help_file)
324 menu.add_command(label=help_label, command=show)
325 return menu
326
327 def refreshCanvas(self):
328 if self.dirty:
329 self.screen.clear()
330 self.dirty=False
331
332 def loadfile(self, filename):
333 self.clearCanvas()
334 turtle.TurtleScreen._RUNNING = False
335 modname = 'turtledemo.' + filename
336 __import__(modname)
337 self.module = sys.modules[modname]
338 with open(self.module.__file__, 'r') as f:
339 chars = f.read()
340 self.text.delete("1.0", "end")
341 self.text.insert("1.0", chars)
342 self.root.title(filename + " - a Python turtle graphics example")
343 self.configGUI(NORMAL, DISABLED, DISABLED,
344 "Press start button", "red")
345 self.state = READY
346
347 def startDemo(self):
348 self.refreshCanvas()
349 self.dirty = True
350 turtle.TurtleScreen._RUNNING = True
351 self.configGUI(DISABLED, NORMAL, DISABLED,
352 "demo running...", "black")
353 self.screen.clear()
354 self.screen.mode("standard")
355 self.state = RUNNING
356
357 try:
358 result = self.module.main()
359 if result == "EVENTLOOP":
360 self.state = EVENTDRIVEN
361 else:
362 self.state = DONE
363 except turtle.Terminator:
364 if self.root is None:
365 return
366 self.state = DONE
367 result = "stopped!"
368 if self.state == DONE:
369 self.configGUI(NORMAL, DISABLED, NORMAL,
370 result)
371 elif self.state == EVENTDRIVEN:
372 self.exitflag = True
373 self.configGUI(DISABLED, NORMAL, DISABLED,
374 "use mouse/keys or STOP", "red")
375
376 def clearCanvas(self):
377 self.refreshCanvas()
378 self.screen._delete("all")
379 self.canvas.config(cursor="")
380 self.configGUI(NORMAL, DISABLED, DISABLED)
381
382 def stopIt(self):
383 if self.exitflag:
384 self.clearCanvas()
385 self.exitflag = False
386 self.configGUI(NORMAL, DISABLED, DISABLED,
387 "STOPPED!", "red")
388 turtle.TurtleScreen._RUNNING = False
389
390 def _destroy(self):
391 turtle.TurtleScreen._RUNNING = False
392 self.root.destroy()
393 self.root = None
394
395
396 def main():
397 demo = DemoWindow()
398 demo.root.mainloop()
399
400 if __name__ == '__main__':
401 main()