pythonpython-2.7pygameturtle-graphicspython-turtle

How to create randomly colored text in Trinket.io/Python?


I am making a game called Gravity code, where the objective of the game is to catch falling items that change the color, speed, size, or shape of the turtle. Where I need a randomly colored title.

# --- imports ---

import turtle
from random import * 

# --- variables ---

font_setup = ("Verdana", 25, "normal")
screen = turtle.Screen()

# --- main ---

title.speed("fastest")
title.hideturtle()
title.penup()
title.goto(-62, 60)
title.write("Gravity", font = font_setup)
title.setpos(-45, 30)
title.write("Code", font = font_setup)

# --- events ---

screen.mainloop()

Solution

  • You can use turtle.onclick(function, mouse_button) to execute function when you click your button.

    onclick needs only function's name without () (so called "callback")

    on_button_click has to get two values - mouse position.

    import turtle
    
    # --- functions ---
    
    def on_button_click(x, y):
        print('button clicked:', x,y)
        button.hideturtle()
        
    # --- main ---
        
    screen = turtle.Screen()
    button = turtle.Turtle()
    
    button.speed("fastest")
    #screen.addshape("icons8-button-100.png") #It's the second button.
    #button.shape("icons8-button-100.png") #https://icons8.com/icons/set/button
    button.left(90) # The second image is the button I'm using.
    button.penup() #It can be resized afer you click download to...
    button.goto(0, -120) # 70 x 70 pixels.
    
    button.onclick(on_button_click, 1)
    
    screen.mainloop()