Onkey function in Python Turtle not working for my input -
previously in program, used inputs in console player enter guesses want use onkey()
function in python 3.6.1 turtle. want detect if player presses key , make string saying "guess='a'". want this:
import turtle canvas=turtle.screen() t=turtle.pen() guess=0 def a(): guess='a' canvas.onkey(a,'a') canvas.listen()
obviously defined function each letter of alphabet. after this, when pressing 'a' , putting 'print(guess)', not printing 'a'.
the short answer forgot global
statement in a()
function it's reference guess
local, not global. here's example implementation:
import turtle def a(): global guess guess += 'a' def b(): global guess guess += 'b' def question(): print(guess) guess = '' canvas = turtle.screen() canvas.onkey(a, 'a') canvas.onkey(b, 'b') canvas.onkey(question, '?') canvas.listen() canvas.mainloop()
you can type 'a' , 'b' as want -- when type '?' string of letters you've built printed.
Comments
Post a Comment