Reputation: 1
The following code is to make a stopwatch in python turtle, and I am having issues with starting and stopping the watch. There is a section in which I use the .onkey
command to try to start the clock with the q
key, and I am having trouble getting this working. Any fixes?
import time,turtle
running = False
cl = 0
def start():
running = True
def stop():
running = False
wn = turtle.Screen()
wn.setup(width=200,height=200)
wn.bgcolor('grey')
wn.tracer(0)
timePen = turtle.Turtle()
timePen.speed(0)
timePen.color('red')
style = ('Courier', 30, 'italic')
timePen.hideturtle()
timePen.penup()
wn.listen()
wn.onkey(start,'q')
wn.onkey(stop,'w')
while running == True:
time.sleep(.01)
cl += .1
timePen.goto(0,0)
timePen.write(round(cl,2), font=style, align='center')
wn.update()
time.sleep(.09)
timePen.clear()
wn.update()
wn.mainloop()
Upvotes: 0
Views: 67
Reputation: 11
the loop wont start because running is set to False
so you must set running to true to start since a loop will start and loop aslong as the condition is true,
the second issue is that the running inside the stop()
and start()
are a copy of the variable thus the real one that was delcared will not changed unless you declare it via global running
inside the def
import time,turtle
running = True
cl = 0
def start():
global running
running = True
def stop():
global running
running = False
wn = turtle.Screen()
wn.setup(width=200,height=200)
wn.bgcolor('grey')
wn.tracer(0)
timePen = turtle.Turtle()
timePen.speed(0)
timePen.color('red')
style = ('Courier', 30, 'italic')
timePen.hideturtle()
timePen.penup()
wn.listen()
wn.onkey(start,'q')
wn.onkey(stop,'w')
while running == True:
time.sleep(.01)
cl += .1
timePen.goto(0,0)
timePen.write(round(cl,2), font=style, align='center')
wn.update()
time.sleep(.09)
timePen.clear()
wn.update()
wn.mainloop()
Upvotes: 1