简体   繁体   English

使用onkey()与Python turtle一起执行多项功能

[英]Use onkey() to do multiple functions with Python turtle

I'm trying to write a basic turtle drawing game/program and I've been using onkey(function, "key") to have the user input keystrokes. 我正在尝试编写一个基本的海龟绘图游戏/程序,并且我一直在使用onkey(function, "key")来让用户输入击键。 Well I wanted the user to be able to change the width of the pen by either hitting the up key to increase the width by one, or the down key to decrease the width by one. 好吧,我希望用户能够通过按向上键将宽度增加1或按下向下键将宽度减小1来改变笔的宽度。 I know I need some kind of loop, but I don't really know where to implement it. 我知道我需要某种循环,但是我真的不知道在哪里实现。

Here's a simple example that will make the turtle walk in a continuous circle while you press up and down arrows to change the pen width: 这是一个简单的示例,当您按下向上和向下箭头以更改笔的宽度时,乌龟可以连续走一圈:

from turtle import Turtle, Screen

def larger():
    size = turtle.pensize()

    if size < 10:
        turtle.pensize(size + 1)

def smaller():
    size = turtle.pensize()

    if size > 1:
        turtle.pensize(size - 1)

def move():
    turtle.circle(150, extent=3)
    screen.ontimer(move, 100)

turtle = Turtle()

screen = Screen()
screen.onkey(larger, "Up")
screen.onkey(smaller, "Down")
screen.listen()

move()

screen.mainloop()

Make sure you click on the window first to make it the key listener. 确保首先单击该窗口以使其成为关键侦听器。

I think you can't, but you can call the function insde the function you bind to the key: 我认为您不能,但是您可以调用函数insde绑定到键的函数:

from turtle import *

def function1():
    do_that = "do that"
    print(do_that)

def function2():
    do_this = "do this"
    print(do_this)
    function1()

onkey(function2, "space")

do this 做这个

do that 去做


It worked for me ;) 它为我工作;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM