You can download this code by clicking the button below.
This code is now available for download.
This function uses the Pyglet library to create a window and continuously redraws a triangle with random colors. The user can exit by pressing the Esc key.
Technology Stack : Pyglet, Random number generation, Graphics drawing
Code Type : Graphical interface
Code Difficulty : Intermediate
def random_color_draw(width, height, window_title):
import pyglet
from pyglet.window import key
from pyglet.graphics import draw
import random
window = pyglet.window.Window(width, height, window_title)
def update(dt):
# Randomly select a new color and redraw the window
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
draw(4, pyglet.graphicsigmple.TRIANGLE_FAN, ('v2f', (0, 0, width, 0, width, height, 0, height)),
('c3B', (255, 255, 255, *color, *color, *color)))
@window.event
def on_key_press(symbol, modifiers):
if symbol == key.ESCAPE:
window.close()
pyglet.clock.schedule_interval(update, 0.1)
pyglet.app.run()