__main__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. if darwin: # Leave Mac button colors alone - #44254.
  134. self.start_btn = Button(root, text=" START ", font=btnfont,
  135. fg='#00cc22', command=self.startDemo)
  136. self.stop_btn = Button(root, text=" STOP ", font=btnfont,
  137. fg='#00cc22', command=self.stopIt)
  138. self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
  139. fg='#00cc22', command = self.clearCanvas)
  140. else:
  141. self.start_btn = Button(root, text=" START ", font=btnfont,
  142. fg="white", disabledforeground = "#fed",
  143. command=self.startDemo)
  144. self.stop_btn = Button(root, text=" STOP ", font=btnfont,
  145. fg="white", disabledforeground = "#fed",
  146. command=self.stopIt)
  147. self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
  148. fg="white", disabledforeground="#fed",
  149. command = self.clearCanvas)
  150. self.output_lbl.grid(row=1, column=0, sticky='news', padx=(0,5))
  151. self.start_btn.grid(row=1, column=1, sticky='ew')
  152. self.stop_btn.grid(row=1, column=2, sticky='ew')
  153. self.clear_btn.grid(row=1, column=3, sticky='ew')
  154. Percolator(self.text).insertfilter(ColorDelegator())
  155. self.dirty = False
  156. self.exitflag = False
  157. if filename:
  158. self.loadfile(filename)
  159. self.configGUI(DISABLED, DISABLED, DISABLED,
  160. "Choose example from menu", "black")
  161. self.state = STARTUP
  162. def onResize(self, event):
  163. cwidth = self.canvas.winfo_width()
  164. cheight = self.canvas.winfo_height()
  165. self.canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
  166. self.canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)
  167. def makeTextFrame(self, root):
  168. self.text_frame = text_frame = Frame(root)
  169. self.text = text = Text(text_frame, name='text', padx=5,
  170. wrap='none', width=45)
  171. color_config(text)
  172. self.vbar = vbar = Scrollbar(text_frame, name='vbar')
  173. vbar['command'] = text.yview
  174. vbar.pack(side=LEFT, fill=Y)
  175. self.hbar = hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
  176. hbar['command'] = text.xview
  177. hbar.pack(side=BOTTOM, fill=X)
  178. text['yscrollcommand'] = vbar.set
  179. text['xscrollcommand'] = hbar.set
  180. text['font'] = tuple(txtfont)
  181. shortcut = 'Command' if darwin else 'Control'
  182. text.bind_all('<%s-minus>' % shortcut, self.decrease_size)
  183. text.bind_all('<%s-underscore>' % shortcut, self.decrease_size)
  184. text.bind_all('<%s-equal>' % shortcut, self.increase_size)
  185. text.bind_all('<%s-plus>' % shortcut, self.increase_size)
  186. text.bind('<Control-MouseWheel>', self.update_mousewheel)
  187. text.bind('<Control-Button-4>', self.increase_size)
  188. text.bind('<Control-Button-5>', self.decrease_size)
  189. text.pack(side=LEFT, fill=BOTH, expand=1)
  190. return text_frame
  191. def makeGraphFrame(self, root):
  192. # t._Screen is a singleton class instantiated or retrieved
  193. # by calling Screen. Since tdemo canvas needs a different
  194. # configuration, we manually set class attributes before
  195. # calling Screen and manually call superclass init after.
  196. turtle._Screen._root = root
  197. self.canvwidth = 1000
  198. self.canvheight = 800
  199. turtle._Screen._canvas = self.canvas = canvas = turtle.ScrolledCanvas(
  200. root, 800, 600, self.canvwidth, self.canvheight)
  201. canvas.adjustScrolls()
  202. canvas._rootwindow.bind('<Configure>', self.onResize)
  203. canvas._canvas['borderwidth'] = 0
  204. self.screen = screen = turtle.Screen()
  205. turtle.TurtleScreen.__init__(screen, canvas)
  206. turtle.RawTurtle.screens = [screen]
  207. return canvas
  208. def set_txtsize(self, size):
  209. txtfont[1] = size
  210. self.text['font'] = tuple(txtfont)
  211. self.output_lbl['text'] = 'Font size %d' % size
  212. def decrease_size(self, dummy=None):
  213. self.set_txtsize(max(txtfont[1] - 1, MINIMUM_FONT_SIZE))
  214. return 'break'
  215. def increase_size(self, dummy=None):
  216. self.set_txtsize(min(txtfont[1] + 1, MAXIMUM_FONT_SIZE))
  217. return 'break'
  218. def update_mousewheel(self, event):
  219. # For wheel up, event.delta = 120 on Windows, -1 on darwin.
  220. # X-11 sends Control-Button-4 event instead.
  221. if (event.delta < 0) == (not darwin):
  222. return self.decrease_size()
  223. else:
  224. return self.increase_size()
  225. def configGUI(self, start, stop, clear, txt="", color="blue"):
  226. if darwin: # Leave Mac button colors alone - #44254.
  227. self.start_btn.config(state=start)
  228. self.stop_btn.config(state=stop)
  229. self.clear_btn.config(state=clear)
  230. else:
  231. self.start_btn.config(state=start,
  232. bg="#d00" if start == NORMAL else "#fca")
  233. self.stop_btn.config(state=stop,
  234. bg="#d00" if stop == NORMAL else "#fca")
  235. self.clear_btn.config(state=clear,
  236. bg="#d00" if clear == NORMAL else "#fca")
  237. self.output_lbl.config(text=txt, fg=color)
  238. def makeLoadDemoMenu(self, master):
  239. menu = Menu(master)
  240. for entry in getExampleEntries():
  241. def load(entry=entry):
  242. self.loadfile(entry)
  243. menu.add_command(label=entry, underline=0,
  244. font=menufont, command=load)
  245. return menu
  246. def makeFontMenu(self, master):
  247. menu = Menu(master)
  248. menu.add_command(label="Decrease (C-'-')", command=self.decrease_size,
  249. font=menufont)
  250. menu.add_command(label="Increase (C-'+')", command=self.increase_size,
  251. font=menufont)
  252. menu.add_separator()
  253. for size in font_sizes:
  254. def resize(size=size):
  255. self.set_txtsize(size)
  256. menu.add_command(label=str(size), underline=0,
  257. font=menufont, command=resize)
  258. return menu
  259. def makeHelpMenu(self, master):
  260. menu = Menu(master)
  261. for help_label, help_file in help_entries:
  262. def show(help_label=help_label, help_file=help_file):
  263. view_text(self.root, help_label, help_file)
  264. menu.add_command(label=help_label, font=menufont, command=show)
  265. return menu
  266. def refreshCanvas(self):
  267. if self.dirty:
  268. self.screen.clear()
  269. self.dirty=False
  270. def loadfile(self, filename):
  271. self.clearCanvas()
  272. turtle.TurtleScreen._RUNNING = False
  273. modname = 'turtledemo.' + filename
  274. __import__(modname)
  275. self.module = sys.modules[modname]
  276. with open(self.module.__file__, 'r') as f:
  277. chars = f.read()
  278. self.text.delete("1.0", "end")
  279. self.text.insert("1.0", chars)
  280. self.root.title(filename + " - a Python turtle graphics example")
  281. self.configGUI(NORMAL, DISABLED, DISABLED,
  282. "Press start button", "red")
  283. self.state = READY
  284. def startDemo(self):
  285. self.refreshCanvas()
  286. self.dirty = True
  287. turtle.TurtleScreen._RUNNING = True
  288. self.configGUI(DISABLED, NORMAL, DISABLED,
  289. "demo running...", "black")
  290. self.screen.clear()
  291. self.screen.mode("standard")
  292. self.state = RUNNING
  293. try:
  294. result = self.module.main()
  295. if result == "EVENTLOOP":
  296. self.state = EVENTDRIVEN
  297. else:
  298. self.state = DONE
  299. except turtle.Terminator:
  300. if self.root is None:
  301. return
  302. self.state = DONE
  303. result = "stopped!"
  304. if self.state == DONE:
  305. self.configGUI(NORMAL, DISABLED, NORMAL,
  306. result)
  307. elif self.state == EVENTDRIVEN:
  308. self.exitflag = True
  309. self.configGUI(DISABLED, NORMAL, DISABLED,
  310. "use mouse/keys or STOP", "red")
  311. def clearCanvas(self):
  312. self.refreshCanvas()
  313. self.screen._delete("all")
  314. self.canvas.config(cursor="")
  315. self.configGUI(NORMAL, DISABLED, DISABLED)
  316. def stopIt(self):
  317. if self.exitflag:
  318. self.clearCanvas()
  319. self.exitflag = False
  320. self.configGUI(NORMAL, DISABLED, DISABLED,
  321. "STOPPED!", "red")
  322. turtle.TurtleScreen._RUNNING = False
  323. def _destroy(self):
  324. turtle.TurtleScreen._RUNNING = False
  325. self.root.destroy()
  326. self.root = None
  327. def main():
  328. demo = DemoWindow()
  329. demo.root.mainloop()
  330. if __name__ == '__main__':
  331. main()