Python中的 turtle.onkey()函数
turtle 模块以面向对象和面向过程的方式提供海龟图形原语。因为它使用 Tkinter 作为底层图形,所以它需要安装一个支持 Tk 的Python版本。
龟.onkey()
该函数用于将 fun 绑定到 key 的 key-release 事件。为了能够注册按键事件,TurtleScreen 必须具有焦点。
句法 :
turtle.onkey(fun, key)
参数:Arguments Description fun a function with no arguments key a string: key (e.g. “a”) or key-symbol (e.g. “space”)
以下是上述方法的实现以及一些示例:
示例 1:
Python3
# import package
import turtle
# method for key call
def fxn():
turtle.forward(40)
# set turtle screen size
sc=turtle.Screen()
sc.setup(600,300)
# motion
turtle.forward(40)
# call method on Right key
turtle.onkey(fxn,'Right')
# to listen by the turtle
turtle.listen()
Python3
# import package
import turtle
# methods with different work
# at different keys
def fxn():
turtle.forward(20)
def fxn1():
turtle.right(90)
def fxn2():
turtle.left(90)
# set screen size
sc=turtle.Screen()
sc.setup(500,300)
# call methods
turtle.onkey(fxn,'space')
turtle.onkey(fxn1,'Right')
turtle.onkey(fxn2,'Left')
# to listen by the turtle
turtle.listen()
输出 :
示例 2:
Python3
# import package
import turtle
# methods with different work
# at different keys
def fxn():
turtle.forward(20)
def fxn1():
turtle.right(90)
def fxn2():
turtle.left(90)
# set screen size
sc=turtle.Screen()
sc.setup(500,300)
# call methods
turtle.onkey(fxn,'space')
turtle.onkey(fxn1,'Right')
turtle.onkey(fxn2,'Left')
# to listen by the turtle
turtle.listen()
输出 :