PageRenderTime 33ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/turtledemo/__main__.py

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