Debian Codegraph @

Lib/turtledemo/__main__.py

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