Richard
Richard

Reputation: 529

Inserting text on_mouse_press using Pyglet

I am trying to insert text into a window using Pyglet following a mouse click. The code below creates the window, prints when I click on the screen but doesn't add the text to the screen.

Any ideas why this is?

Thanks in advance.

import pyglet
from pyglet.gl import *
from pyglet.window import mouse


class Drainage_Window(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_minimum_size(300, 300)

    def on_draw(self):
        self.clear()


if __name__ == '__main__':
    window = Drainage_Window(width=1920 // 4, height=1080//4,
                             caption="Drainage Network", resizable=True)
    glClearColor(0.7, 0.7, 1, 1)

    @window.event
    def on_mouse_press(x, y, button, modifiers):
        if button == mouse.LEFT:
            print('The left mouse button was pressed.')
            label = pyglet.text.Label('Click!',
                                  font_name='Times New Roman',
                                  font_size=16,
                                  x=x, y=y,
                                  anchor_x='center', anchor_y='center')

            window.push_handlers(pyglet.window.event.WindowEventLogger())

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

    pyglet.app.run()

Upvotes: 1

Views: 617

Answers (1)

Attila Toth
Attila Toth

Reputation: 469

I just rearranged your code a bit, moved the mouse press event in the window class. The label starts as None, and when the left mouse button is pressed, the label will become a Label object. In the draw method added a simple if check, so that the label is only drawn when it is not None. And it works now.

import pyglet
from pyglet.gl import *
from pyglet.window import mouse


class Drainage_Window(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_minimum_size(300, 300)

        self.label = None

    def on_mouse_press(self, x, y, button, modifiers):
        if button == mouse.LEFT:
            self.label = pyglet.text.Label('Click!',
                                  font_name='Times New Roman',
                                  font_size=16,
                                  x=x, y=y,
                                  anchor_x='center', anchor_y='center')

    def on_draw(self):
        self.clear()
        if self.label:
            self.label.draw()


if __name__ == '__main__':
    window = Drainage_Window(width=1920 // 4, height=1080//4,
                             caption="Drainage Network", resizable=True)
    glClearColor(0.7, 0.7, 1, 1)

    pyglet.app.run()

Upvotes: 1

Related Questions