问题
I am trying to add 1 every time I release a key:
from turtle import *
import turtle
turtle1 = Turtle()
screen = turtle1.getscreen()
goPressed = False
imported Turtle...
currentWatts=0
def onaclicked():
global currentWatts
currentWatts+=1
print (currentWatts)
defined my function to be run when the key: 1, is released
turtle.onkeyrelease(onaclicked, "1")
for some reason onkeyrelease
isn't there even though I imported Turtle and checked in Python documentation. It SHOULD work, shouldn't it? Did I improperly import? Can you please help me?
The reason I want it to be onkeyrelease
instead of onkey
, is because it is for a game. With onkey
, when you hold your finger on the key, it adds 1 to currentWatts every around 0.25 seconds. You could cheat by placing something on the key so I want it only to add 1 when you release the key.
回答1:
You've several problems with your code: you import turtle two different ways which confuses things; onkeyrelease()
is really a method of the screen/window, not a turtle; you didn't call listen()
which allows keystrokes to be processed. The following should work in Python 3:
from turtle import Turtle, Screen, mainloop
def onaclicked():
global currentWatts
currentWatts += 1
print(currentWatts)
currentWatts = 0
screen = Screen()
screen.onkeyrelease(onaclicked, "1")
screen.listen()
mainloop()
Make sure to click on the window once before you start typing to make it active.
If you're using Python 2, which I suspect from the error message you got, then replace the Python 3 alias onkeyrelease
with onkey
:
The method Screen.onkeypress() has been added as a complement to Screen.onkey() which in fact binds actions to the keyrelease event. Accordingly the latter has got an alias: Screen.onkeyrelease().
This change should work the same in both versions. Using onkeyrelease
instead of onkey
wasn't going fix your holding a finger on the key issue.
when you hold your finger on the key, it adds 1 to currentWatts every around 0.25 seconds. You could cheat by placing something on the key so I want it only to add 1 when you release
It appears that automatic key repeats are handled by the operating system and may need to be disabled external to Python, depending on the OS. Some example links:
- Apple OSX: Set how quickly a key repeats
- Ubuntu: Turn off repeated key presses
- X-Windows from Python: key repeat in tkinter
来源:https://stackoverflow.com/questions/44345100/turtle-gives-error-attributeerror-turtle-object-has-no-attribute-onkeyrelea