You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pyglet技术问题:如何将line.draw_line()整合至on_draw()事件循环?

问题解决:Pyglet线条闪烁与绘制逻辑整合

问题原因

  • 线条闪烁:原代码在on_mouse_press中直接调用draw_line(),但Pyglet的on_draw事件会每一帧清屏重绘,这条线仅在鼠标按下的瞬间被绘制一次,后续帧不会重绘,导致线条闪烁或直接消失。
  • 无法整合到on_draw:DrawLines类的draw_line方法错误使用了@window.event装饰器,且没有持久化存储线条实例,on_draw无法获取到需要绘制的线条对象。

修复后的代码

import pyglet

window = pyglet.window.Window(width=1900, height=1050, fullscreen=False, caption="Dots", resizable=True, vsync=True)

# 全局列表存储所有需要绘制的线条
lines = []

class DrawLines:
    def __init__(self, x_coord, y_coord, x2_coord, y2_coord, color):
        self.Line = pyglet.shapes.Line(
            x=x_coord, y=y_coord, 
            x2=x2_coord, y2=y2_coord,
            color=color, width=5
        )

    def draw_line(self):
        self.Line.draw()


ball = pyglet.shapes.Circle(x=0, y=0, radius=10, segments=10)
ball2 = pyglet.shapes.Circle(x=200, y=200, radius=10, segments=20)


def calculate_distance(x1, x2, y1, y2):
    return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5


@window.event
def on_mouse_press(x, y, symbol, modifiers):
    global lines
    ball1_dst = calculate_distance(x, ball.x, y, ball.y)
    ball2_dst = calculate_distance(x, ball2.x, y, ball2.y)
    
    if ball1_dst > ball2_dst:
        line = DrawLines(x, y, ball2.x, ball2.y, [0, 255, 255, 255])
    else:
        line = DrawLines(x, y, ball.x, ball.y, [255, 0, 255, 255])
    
    lines.append(line)


@window.event
def on_draw():
    window.clear()
    # 固定ball在窗口中心
    ball.x = window.width / 2
    ball.y = window.height / 2
    ball.draw()
    ball2.draw()
    # 遍历绘制所有线条
    for line in lines:
        line.draw_line()


pyglet.app.run()

关键修改点

  1. 新增全局列表lines,用于持久化存储所有需要绘制的线条实例。
  2. 移除DrawLines类中错误的@window.event装饰器,让draw_line仅负责绘制自身的线条对象。
  3. 在on_mouse_press中创建线条实例后,将其添加到lines列表中。
  4. 在on_draw中遍历lines列表,逐一调用每个线条的draw_line方法,确保每一帧都重绘所有线条,解决闪烁问题。

内容的提问来源于stack exchange,提问作者UtsavLMFAO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:42:27