James Fraser
James Fraser

Reputation: 15

Toggle between functions when key is pressed using Python

Hey Guys I am doing an assingment for uni and I have to make a colouring book which enables the user to swap between two modes using the space key. In the first mode the user must be able to move the turtle with out drawing any lines and the second mode must initiate the paint brush mode where the user can draw.I want to be able to toggle between penup() and the pendown() turtle functions when the space button is pressed. Any ideas?

This is what I have so far:

from turtle import *
bgpic("Colour_A_Turkey.gif") # change this to change the picture

# PUT YOUR CODE HERE
setup(800,600)
home()
pen_size = 2
color("red")
title("Colouring Book")
speed("fastest") # Doesn't make any difference to accuracy, just makes turtle turn animation faster.
drawdist=10 # Distance in pixels pen travels when arrow key is pressed

penup()
###################BUTTON INSTRUCTIONS########################
def move_up():
        seth(90)
        forward(drawdist)

def move_down():
        seth(270)
        forward(drawdist)

def move_left():
        seth(180)
        forward(drawdist)

def move_right():
        seth(0)
        forward(drawdist)

def space_bar():

        if isdown()==True:
                penup()

        if isdown()==False:
                       pendown()
####Change pen color####
def red():
        color("red")

def green():
        color("green")

def blue():
        color("blue")


################BUTTON TRIGGERS##################
s= getscreen()

s.onkey(move_up,"Up")

s.onkey(move_down,"Down")

s.onkey(move_left,"Left")

s.onkey(move_right,"Right")

s.onkey(space_bar,"space")

s.onkey(red,"r")

s.onkey(green,"g")

s.onkey(blue,"b")

listen()

done()

Upvotes: 1

Views: 3410

Answers (3)

TC1080
TC1080

Reputation: 1

This is how you toggle between pen up and pen down.

up = False

def pen_up():

    global up
    up = not up
    if up:
        t.penup()
    else:
        t.pendown()

ts.onkey(pen_up, 'space')

Upvotes: 0

jamylak
jamylak

Reputation: 133664

from itertools import cycle

funcs = cycle([f1, f2])
next(funcs)() # alternates

Upvotes: 1

avrahamy
avrahamy

Reputation: 191

When space_bar is called, isdown() is always true.
Do you want to toggle or draw only when the spacebar is pressed?

If you want to toggle, here's what you can do:

current_state = penup
next_state = pendown
def space_bar():
    global current_state, next_state
    next_state()
    current_state, next_state = next_state, current_state

Upvotes: 1

Related Questions