简体   繁体   中英

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. 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. 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:

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 ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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