Try to fix transient refleaks in test_asynchat.
[python.git] / Demo / turtle / turtleDemo.py
blob38a44e0ea137d4a65c5603f00a0d247edaf92ebc
1 #!/usr/bin/python
2 import sys
3 import os
5 from Tkinter import *
6 from idlelib.Percolator import Percolator
7 from idlelib.ColorDelegator import ColorDelegator
8 from idlelib.textView import TextViewer
10 import turtle
11 import time
13 STARTUP = 1
14 READY = 2
15 RUNNING = 3
16 DONE = 4
17 EVENTDRIVEN = 5
19 menufont = ("Arial", 12, NORMAL)
20 btnfont = ("Arial", 12, 'bold')
21 txtfont = ('Lucida Console', 8, 'normal')
23 def getExampleEntries():
24 cwd = os.getcwd()
25 if "turtleDemo.py" not in os.listdir(cwd):
26 print "Directory of turtleDemo must be current working directory!"
27 print "But in your case this is", cwd
28 sys.exit()
29 entries1 = [entry for entry in os.listdir(cwd) if
30 entry.startswith("tdemo_") and
31 not entry.endswith(".pyc")]
32 entries2 = []
33 for entry in entries1:
34 if entry.endswith(".py"):
35 entries2.append(entry)
36 else:
37 path = os.path.join(cwd,entry)
38 sys.path.append(path)
39 subdir = [entry]
40 scripts = [script for script in os.listdir(path) if
41 script.startswith("tdemo_") and
42 script.endswith(".py")]
43 entries2.append(subdir+scripts)
44 return entries2
46 def showDemoHelp():
47 TextViewer(demo.root, "Help on turtleDemo", "demohelp.txt")
49 def showAboutDemo():
50 TextViewer(demo.root, "About turtleDemo", "about_turtledemo.txt")
52 def showAboutTurtle():
53 TextViewer(demo.root, "About the new turtle module", "about_turtle.txt")
55 class DemoWindow(object):
57 def __init__(self, filename=None): #, root=None):
58 self.root = root = turtle._root = Tk()
59 root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
61 #################
62 self.mBar = Frame(root, relief=RAISED, borderwidth=2)
63 self.mBar.pack(fill=X)
65 self.ExamplesBtn = self.makeLoadDemoMenu()
66 self.OptionsBtn = self.makeHelpMenu()
67 self.mBar.tk_menuBar(self.ExamplesBtn, self.OptionsBtn) #, QuitBtn)
69 root.title('Python turtle-graphics examples')
70 #################
71 self.left_frame = left_frame = Frame(root)
72 self.text_frame = text_frame = Frame(left_frame)
73 self.vbar = vbar =Scrollbar(text_frame, name='vbar')
74 self.text = text = Text(text_frame,
75 name='text', padx=5, wrap='none',
76 width=45)
77 vbar['command'] = text.yview
78 vbar.pack(side=LEFT, fill=Y)
79 #####################
80 self.hbar = hbar =Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
81 hbar['command'] = text.xview
82 hbar.pack(side=BOTTOM, fill=X)
83 #####################
84 text['yscrollcommand'] = vbar.set
85 text.config(font=txtfont)
86 text.config(xscrollcommand=hbar.set)
87 text.pack(side=LEFT, fill=Y, expand=1)
88 #####################
89 self.output_lbl = Label(left_frame, height= 1,text=" --- ", bg = "#ddf",
90 font = ("Arial", 16, 'normal'))
91 self.output_lbl.pack(side=BOTTOM, expand=0, fill=X)
92 #####################
93 text_frame.pack(side=LEFT, fill=BOTH, expand=0)
94 left_frame.pack(side=LEFT, fill=BOTH, expand=0)
95 self.graph_frame = g_frame = Frame(root)
97 turtle._Screen._root = g_frame
98 turtle._Screen._canvas = turtle.ScrolledCanvas(g_frame, 800, 600, 1000, 800)
99 #xturtle.Screen._canvas.pack(expand=1, fill="both")
100 self.screen = _s_ = turtle.Screen()
101 turtle.TurtleScreen.__init__(_s_, _s_._canvas)
102 self.scanvas = _s_._canvas
103 #xturtle.RawTurtle.canvases = [self.scanvas]
104 turtle.RawTurtle.screens = [_s_]
106 self.scanvas.pack(side=TOP, fill=BOTH, expand=1)
108 self.btn_frame = btn_frame = Frame(g_frame, height=100)
109 self.start_btn = Button(btn_frame, text=" START ", font=btnfont, fg = "white",
110 disabledforeground = "#fed", command=self.startDemo)
111 self.start_btn.pack(side=LEFT, fill=X, expand=1)
112 self.stop_btn = Button(btn_frame, text=" STOP ", font=btnfont, fg = "white",
113 disabledforeground = "#fed", command = self.stopIt)
114 self.stop_btn.pack(side=LEFT, fill=X, expand=1)
115 self.clear_btn = Button(btn_frame, text=" CLEAR ", font=btnfont, fg = "white",
116 disabledforeground = "#fed", command = self.clearCanvas)
117 self.clear_btn.pack(side=LEFT, fill=X, expand=1)
119 self.btn_frame.pack(side=TOP, fill=BOTH, expand=0)
120 self.graph_frame.pack(side=TOP, fill=BOTH, expand=1)
122 Percolator(text).insertfilter(ColorDelegator())
123 self.dirty = False
124 self.exitflag = False
125 if filename:
126 self.loadfile(filename)
127 self.configGUI(NORMAL, DISABLED, DISABLED, DISABLED,
128 "Choose example from menu", "black")
129 self.state = STARTUP
131 def _destroy(self):
132 self.root.destroy()
133 sys.exit()
135 def configGUI(self, menu, start, stop, clear, txt="", color="blue"):
136 self.ExamplesBtn.config(state=menu)
138 self.start_btn.config(state=start)
139 if start==NORMAL:
140 self.start_btn.config(bg="#d00")
141 else:
142 self.start_btn.config(bg="#fca")
144 self.stop_btn.config(state=stop)
145 if stop==NORMAL:
146 self.stop_btn.config(bg="#d00")
147 else:
148 self.stop_btn.config(bg="#fca")
149 self.clear_btn.config(state=clear)
151 self.clear_btn.config(state=clear)
152 if clear==NORMAL:
153 self.clear_btn.config(bg="#d00")
154 else:
155 self.clear_btn.config(bg="#fca")
157 self.output_lbl.config(text=txt, fg=color)
160 def makeLoadDemoMenu(self):
161 CmdBtn = Menubutton(self.mBar, text='Examples', underline=0, font=menufont)
162 CmdBtn.pack(side=LEFT, padx="2m")
163 CmdBtn.menu = Menu(CmdBtn)
165 for entry in getExampleEntries():
166 def loadexample(x):
167 def emit():
168 self.loadfile(x)
169 return emit
170 if isinstance(entry,str):
171 CmdBtn.menu.add_command(label=entry[6:-3], underline=0, font=menufont,
172 command=loadexample(entry))
173 else:
174 _dir, entries = entry[0], entry[1:]
175 CmdBtn.menu.choices = Menu(CmdBtn.menu)
176 for e in entries:
177 CmdBtn.menu.choices.add_command(label=e[6:-3], underline=0, font=menufont,
178 command = loadexample(os.path.join(_dir,e)))
180 CmdBtn.menu.add_cascade(label=_dir[6:],
181 menu = CmdBtn.menu.choices, font=menufont )
183 CmdBtn['menu'] = CmdBtn.menu
184 return CmdBtn
187 def makeHelpMenu(self):
188 CmdBtn = Menubutton(self.mBar, text='Help', underline=0, font = menufont)
189 CmdBtn.pack(side=LEFT, padx='2m')
190 CmdBtn.menu = Menu(CmdBtn)
192 CmdBtn.menu.add_command(label='About turtle.py', font=menufont, command=showAboutTurtle)
193 CmdBtn.menu.add_command(label='turtleDemo - Help', font=menufont, command=showDemoHelp)
194 CmdBtn.menu.add_command(label='About turtleDemo', font=menufont, command=showAboutDemo)
196 CmdBtn['menu'] = CmdBtn.menu
197 return CmdBtn
199 def refreshCanvas(self):
200 if not self.dirty: return
201 self.screen.clear()
202 #self.screen.mode("standard")
203 self.dirty=False
205 def loadfile(self,filename):
206 self.refreshCanvas()
207 if os.path.exists(filename) and not os.path.isdir(filename):
208 # load and display file text
209 f = open(filename,'r')
210 chars = f.read()
211 f.close()
212 self.text.delete("1.0", "end")
213 self.text.insert("1.0",chars)
214 direc, fname = os.path.split(filename)
215 self.root.title(fname[6:-3]+" - an xturtle example")
216 self.module = __import__(fname[:-3])
217 reload(self.module)
218 self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED,
219 "Press start button", "red")
220 self.state = READY
222 def startDemo(self):
223 self.refreshCanvas()
224 self.dirty = True
225 turtle.TurtleScreen._RUNNING = True
226 self.configGUI(DISABLED, DISABLED, NORMAL, DISABLED,
227 "demo running...", "black")
228 self.screen.clear()
229 self.screen.mode("standard")
230 self.state = RUNNING
232 try:
233 result = self.module.main()
234 if result == "EVENTLOOP":
235 self.state = EVENTDRIVEN
236 else:
237 self.state = DONE
238 except turtle.Terminator:
239 self.state = DONE
240 result = "stopped!"
241 if self.state == DONE:
242 self.configGUI(NORMAL, NORMAL, DISABLED, NORMAL,
243 result)
244 elif self.state == EVENTDRIVEN:
245 self.exitflag = True
246 self.configGUI(DISABLED, DISABLED, NORMAL, DISABLED,
247 "use mouse/keys or STOP", "red")
249 def clearCanvas(self):
250 self.refreshCanvas()
251 self.scanvas.config(cursor="")
252 self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED)
254 def stopIt(self):
255 if self.exitflag:
256 self.clearCanvas()
257 self.exitflag = False
258 self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED,
259 "STOPPED!", "red")
260 turtle.TurtleScreen._RUNNING = False
261 #print "stopIT: exitflag = True"
262 else:
263 turtle.TurtleScreen._RUNNING = False
264 #print "stopIt: exitflag = False"
266 if __name__ == '__main__':
267 demo = DemoWindow()
268 RUN = True
269 while RUN:
270 try:
271 print "ENTERING mainloop"
272 demo.root.mainloop()
273 except AttributeError:
274 print "CRASH!!!- WAIT A MOMENT!"
275 time.sleep(0.3)
276 print "GOING ON .."
277 demo.refreshCanvas()
278 ## time.sleep(1)
279 except:
280 RUN = FALSE