以下代碼在不同環境中的行爲有所不同。Python Turtle按鍵事件不重複
在我的Windows機器上(Windows 10,Python 3.6),每次按鍵都會創建一個響應,然後再次按下某個鍵之前什麼也沒有發生。
關於「Python飾品」(https://trinket.io/python)我不需要重複按鍵,因爲按住鍵可以創建重複事件。
我知道Trinket版本是一個JS實現,但這是否完全解釋了這種差異?程序在Linux或OS上的行爲是否相同?
更重要的是,有沒有辦法使它在Windows上工作,以便按住按鍵創建重複事件?
# import the turtle module so we can use all the neat code it contains
import turtle
# Create a variable `tina` that is a Turtle() object. Set shape to 'turtle'
tina = turtle.Turtle()
tina.shape('turtle')
# Create a variable `screen`, a Screen() object, that will handle keyss
screen = turtle.Screen()
# Define functions for each arrow key
def go_left():
tina.left(7)
def go_right():
tina.right(7)
def go_forward():
tina.forward(10)
def go_backward():
tina.backward(10)
# Tell the program which functions go with which keys
screen.onkey(go_left, 'Left')
screen.onkey(go_right, 'Right')
screen.onkey(go_forward, 'Up')
screen.onkey(go_backward, 'Down')
# Tell the screen to listen for key presses
screen.listen()
turtle.done()
你可以嘗試把在那裏的條件設置「真」在while循環的screen.listen()時,鍵被按下並保持'真',直到它被釋放爲止...... –
@Drt,你覺得'screen.listen()'做什麼?它只允許窗口接收事件,並且通常每個程序調用一次(除非正在使用'textinput()'和'numinput()'面板)。它不是停止並等待關鍵事件的東西,也不是可以直接禁用。 – cdlane