Pyglet-based Text Position Update on Mouse Click

  • Share this:

Code introduction


This code uses the Pyglet library to create a window and displays text at the position where the mouse is clicked. When the left mouse button is clicked, the position of the text is updated to the click position.


Technology Stack : Pyglet, event handling, text rendering

Code Type : Graphical interface application

Code Difficulty : Intermediate


                
                    
import pyglet
from pyglet.window import key

def draw_text_on_click(x, y, text):
    window = pyglet.window.Window()
    label = pyglet.text.Label(text,
                              font_name='Arial',
                              font_size=36,
                              color=(255, 255, 255, 255),
                              x=x, y=y)

    @window.event
    def on_draw():
        window.clear()
        label.draw()

    @window.event
    def on_mouse_press(x, y, button, modifiers):
        if button == key.LEFT:
            label.x = x
            label.y = y

    pyglet.app.run()