__main__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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.ColorDelegator 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. import time
  73. demo_dir = os.path.dirname(os.path.abspath(__file__))
  74. darwin = sys.platform == 'darwin'
  75. STARTUP = 1
  76. READY = 2
  77. RUNNING = 3
  78. DONE = 4
  79. EVENTDRIVEN = 5
  80. menufont = ("Arial", 12, NORMAL)
  81. btnfont = ("Arial", 12, 'bold')
  82. txtfont = ['Lucida Console', 10, 'normal']
  83. MINIMUM_FONT_SIZE = 6
  84. MAXIMUM_FONT_SIZE = 100
  85. font_sizes = [8, 9, 10, 11, 12, 14, 18, 20, 22, 24, 30]
  86. def getExampleEntries():
  87. return [entry[:-3] for entry in os.listdir(demo_dir) if
  88. entry.endswith(".py") and entry[0] != '_']
  89. help_entries = ( # (help_label, help_doc)
  90. ('Turtledemo help', __doc__),
  91. ('About turtledemo', about_turtledemo),
  92. ('About turtle module', turtle.__doc__),
  93. )
  94. class DemoWindow(object):
  95. def __init__(self, filename=None):
  96. self.root = root = turtle._root = Tk()
  97. root.title('Python turtle-graphics examples')
  98. root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
  99. if darwin:
  100. import subprocess
  101. # Make sure we are the currently activated OS X application
  102. # so that our menu bar appears.
  103. p = subprocess.Popen(
  104. [
  105. 'osascript',
  106. '-e', 'tell application "System Events"',
  107. '-e', 'set frontmost of the first process whose '
  108. 'unix id is {} to true'.format(os.getpid()),
  109. '-e', 'end tell',
  110. ],
  111. stderr=subprocess.DEVNULL,
  112. stdout=subprocess.DEVNULL,)
  113. root.grid_rowconfigure(0, weight=1)
  114. root.grid_columnconfigure(0, weight=1)
  115. root.grid_columnconfigure(1, minsize=90, weight=1)
  116. root.grid_columnconfigure(2, minsize=90, weight=1)
  117. root.grid_columnconfigure(3, minsize=90, weight=1)
  118. self.mBar = Menu(root, relief=RAISED, borderwidth=2)
  119. self.mBar.add_cascade(menu=self.makeLoadDemoMenu(self.mBar),
  120. label='Examples', underline=0)
  121. self.mBar.add_cascade(menu=self.makeFontMenu(self.mBar),
  122. label='Fontsize', underline=0)
  123. self.mBar.add_cascade(menu=self.makeHelpMenu(self.mBar),
  124. label='Help', underline=0)
  125. root['menu'] = self.mBar
  126. pane = PanedWindow(orient=HORIZONTAL, sashwidth=5,
  127. sashrelief=SOLID, bg='#ddd')
  128. pane.add(self.makeTextFrame(pane))
  129. pane.add(self.makeGraphFrame(pane))
  130. pane.grid(row=0, columnspan=4, sticky='news')
  131. self.output_lbl = Label(root, height= 1, text=" --- ", bg="#ddf",
  132. font=("Arial", 16, 'normal'), borderwidth=2,
  133. relief=RIDGE)
  134. self.start_btn = Button(root, text=" START ", font=btnfont,
  135. fg="white", disabledforeground = "#fed",
  136. command=self.startDemo)
  137. self.stop_btn = Button(root, text=" STOP ", font=btnfont,
  138. fg="white", disabledforeground = "#fed",
  139. command=self.stopIt)
  140. self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
  141. fg="white", disabledforeground="#fed",
  142. command = self.clearCanvas)
  143. self.output_lbl.grid(row=1, column=0, sticky='news', padx=(0,5))
  144. self.start_btn.grid(row=1, column=1, sticky='ew')
  145. self.stop_btn.grid(row=1, column=2, sticky='ew')
  146. self.clear_btn.grid(row=1, column=3, sticky='ew')
  147. Percolator(self.text).insertfilter(ColorDelegator())
  148. self.dirty = False
  149. self.exitflag = False
  150. if filename:
  151. self.loadfile(filename)
  152. self.configGUI(DISABLED, DISABLED, DISABLED,
  153. "Choose example from menu", "black")
  154. self.state = STARTUP
  155. def onResize(self, event):
  156. cwidth = self._canvas.winfo_width()
  157. cheight = self._canvas.winfo_height()
  158. self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
  159. self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)
  160. def makeTextFrame(self, root):
  161. self.text_frame = text_frame = Frame(root)
  162. self.text = text = Text(text_frame, name='text', padx=5,
  163. wrap='none', width=45)
  164. color_config(text)
  165. self.vbar = vbar = Scrollbar(text_frame, name='vbar')
  166. vbar['command'] = text.yview
  167. vbar.pack(side=LEFT, fill=Y)
  168. self.hbar = hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
  169. hbar['command'] = text.xview
  170. hbar.pack(side=BOTTOM, fill=X)
  171. text['yscrollcommand'] = vbar.set
  172. text['xscrollcommand'] = hbar.set
  173. text['font'] = tuple(txtfont)
  174. shortcut = 'Command' if darwin else 'Control'
  175. text.bind_all('<%s-minus>' % shortcut, self.decrease_size)
  176. text.bind_all('<%s-underscore>' % shortcut, self.decrease_size)
  177. text.bind_all('<%s-equal>' % shortcut, self.increase_size)
  178. text.bind_all('<%s-plus>' % shortcut, self.increase_size)
  179. text.bind('<Control-MouseWheel>', self.update_mousewheel)
  180. text.bind('<Control-Button-4>', self.increase_size)
  181. text.bind('<Control-Button-5>', self.decrease_size)
  182. text.pack(side=LEFT, fill=BOTH, expand=1)
  183. return text_frame
  184. def makeGraphFrame(self, root):
  185. turtle._Screen._root = root
  186. self.canvwidth = 1000
  187. self.canvheight = 800
  188. turtle._Screen._canvas = self._canvas = canvas = turtle.ScrolledCanvas(
  189. root, 800, 600, self.canvwidth, self.canvheight)
  190. canvas.adjustScrolls()
  191. canvas._rootwindow.bind('<Configure>', self.onResize)
  192. canvas._canvas['borderwidth'] = 0
  193. self.screen = _s_ = turtle.Screen()
  194. turtle.TurtleScreen.__init__(_s_, _s_._canvas)
  195. self.scanvas = _s_._canvas
  196. turtle.RawTurtle.screens = [_s_]
  197. return canvas
  198. def set_txtsize(self, size):
  199. txtfont[1] = size
  200. self.text['font'] = tuple(txtfont)
  201. self.output_lbl['text'] = 'Font size %d' % size
  202. def decrease_size(self, dummy=None):
  203. self.set_txtsize(max(txtfont[1] - 1, MINIMUM_FONT_SIZE))
  204. return 'break'
  205. def increase_size(self, dummy=None):
  206. self.set_txtsize(min(txtfont[1] + 1, MAXIMUM_FONT_SIZE))
  207. return 'break'
  208. def update_mousewheel(self, event):
  209. # For wheel up, event.delte = 120 on Windows, -1 on darwin.
  210. # X-11 sends Control-Button-4 event instead.
  211. if (event.delta < 0) == (not darwin):
  212. return self.decrease_size()
  213. else:
  214. return self.increase_size()
  215. def configGUI(self, start, stop, clear, txt="", color="blue"):
  216. self.start_btn.config(state=start,
  217. bg="#d00" if start == NORMAL else "#fca")
  218. self.stop_btn.config(state=stop,
  219. bg="#d00" if stop == NORMAL else "#fca")
  220. self.clear_btn.config(state=clear,
  221. bg="#d00" if clear == NORMAL else"#fca")
  222. self.output_lbl.config(text=txt, fg=color)
  223. def makeLoadDemoMenu(self, master):
  224. menu = Menu(master)
  225. for entry in getExampleEntries():
  226. def load(entry=entry):
  227. self.loadfile(entry)
  228. menu.add_command(label=entry, underline=0,
  229. font=menufont, command=load)
  230. return menu
  231. def makeFontMenu(self, master):
  232. menu = Menu(master)
  233. menu.add_command(label="Decrease (C-'-')", command=self.decrease_size,
  234. font=menufont)
  235. menu.add_command(label="Increase (C-'+')", command=self.increase_size,
  236. font=menufont)
  237. menu.add_separator()
  238. for size in font_sizes:
  239. def resize(size=size):
  240. self.set_txtsize(size)
  241. menu.add_command(label=str(size), underline=0,
  242. font=menufont, command=resize)
  243. return menu
  244. def makeHelpMenu(self, master):
  245. menu = Menu(master)
  246. for help_label, help_file in help_entries:
  247. def show(help_label=help_label, help_file=help_file):
  248. view_text(self.root, help_label, help_file)
  249. menu.add_command(label=help_label, font=menufont, command=show)
  250. return menu
  251. def refreshCanvas(self):
  252. if self.dirty:
  253. self.screen.clear()
  254. self.dirty=False
  255. def loadfile(self, filename):
  256. self.clearCanvas()
  257. turtle.TurtleScreen._RUNNING = False
  258. modname = 'turtledemo.' + filename
  259. __import__(modname)
  260. self.module = sys.modules[modname]
  261. with open(self.module.__file__, 'r') as f:
  262. chars = f.read()
  263. self.text.delete("1.0", "end")
  264. self.text.insert("1.0", chars)
  265. self.root.title(filename + " - a Python turtle graphics example")
  266. self.configGUI(NORMAL, DISABLED, DISABLED,
  267. "Press start button", "red")
  268. self.state = READY
  269. def startDemo(self):
  270. self.refreshCanvas()
  271. self.dirty = True
  272. turtle.TurtleScreen._RUNNING = True
  273. self.configGUI(DISABLED, NORMAL, DISABLED,
  274. "demo running...", "black")
  275. self.screen.clear()
  276. self.screen.mode("standard")
  277. self.state = RUNNING
  278. try:
  279. result = self.module.main()
  280. if result == "EVENTLOOP":
  281. self.state = EVENTDRIVEN
  282. else:
  283. self.state = DONE
  284. except turtle.Terminator:
  285. if self.root is None:
  286. return
  287. self.state = DONE
  288. result = "stopped!"
  289. if self.state == DONE:
  290. self.configGUI(NORMAL, DISABLED, NORMAL,
  291. result)
  292. elif self.state == EVENTDRIVEN:
  293. self.exitflag = True
  294. self.configGUI(DISABLED, NORMAL, DISABLED,
  295. "use mouse/keys or STOP", "red")
  296. def clearCanvas(self):
  297. self.refreshCanvas()
  298. self.screen._delete("all")
  299. self.scanvas.config(cursor="")
  300. self.configGUI(NORMAL, DISABLED, DISABLED)
  301. def stopIt(self):
  302. if self.exitflag:
  303. self.clearCanvas()
  304. self.exitflag = False
  305. self.configGUI(NORMAL, DISABLED, DISABLED,
  306. "STOPPED!", "red")
  307. turtle.TurtleScreen._RUNNING = False
  308. def _destroy(self):
  309. turtle.TurtleScreen._RUNNING = False
  310. self.root.destroy()
  311. self.root = None
  312. def main():
  313. demo = DemoWindow()
  314. demo.root.mainloop()
  315. if __name__ == '__main__':
  316. main()