Pyglet中点击打开的新窗口图形闪烁问题求助
解决Pyglet多窗口图形闪烁问题

运行以下代码后,初始窗口与GIF中一致,点击后会打开新窗口,但新窗口内的图形存在闪烁现象。已尝试在绘制前清除两个窗口,但仍不确定闪烁原因。
import pyglet from pyglet import shapes from pyglet.window import mouse window = pyglet.window.Window(960, 540) window2 = pyglet.window.Window(960, 540, visible=False) batch = pyglet.graphics.Batch() batch2 = pyglet.graphics.Batch() class window_one(): circle = shapes.Circle(700, 150, 100, color=(50, 225, 30), batch=batch) square = shapes.Rectangle(200, 200, 200, 200, color=(55, 55, 255), batch=batch) rectangle = shapes.Rectangle(250, 300, 400, 200, color=(255, 22, 20), batch=batch) rectangle.opacity = 128 rectangle.rotation = 33 line2 = shapes.Line(150, 150, 444, 111, width=4, color=(200, 20, 20), batch=batch) class window_two(): line = shapes.Line(100, 100, 100, 200, width=19, batch=batch2) star = shapes.Star(800, 400, 60, 40, num_spikes=20, color=(255, 255, 0), batch=batch2) @window.event def on_draw(): window.clear() window2.clear() batch.draw() @window.event def on_mouse_press(x,y,button, modifier): window2.set_visible(True) batch2.draw() pyglet.app.run()
问题原因
- 错误在第一个窗口的
on_draw方法里清除第二个窗口,不符合Pyglet多窗口的独立绘制逻辑,每个窗口应该单独处理自身的绘制流程。 - 仅在鼠标点击时调用一次
batch2.draw(),但Pyglet窗口在被遮挡、恢复显示或系统触发刷新时,会重新调用on_draw事件,此时没有对应绘制逻辑,就会导致图形丢失或闪烁。
修复后的代码
import pyglet from pyglet import shapes from pyglet.window import mouse window = pyglet.window.Window(960, 540) window2 = pyglet.window.Window(960, 540, visible=False) batch = pyglet.graphics.Batch() batch2 = pyglet.graphics.Batch() class window_one(): circle = shapes.Circle(700, 150, 100, color=(50, 225, 30), batch=batch) square = shapes.Rectangle(200, 200, 200, 200, color=(55, 55, 255), batch=batch) rectangle = shapes.Rectangle(250, 300, 400, 200, color=(255, 22, 20), batch=batch) rectangle.opacity = 128 rectangle.rotation = 33 line2 = shapes.Line(150, 150, 444, 111, width=4, color=(200, 20, 20), batch=batch) class window_two(): line = shapes.Line(100, 100, 100, 200, width=19, batch=batch2) star = shapes.Star(800, 400, 60, 40, num_spikes=20, color=(255, 255, 0), batch=batch2) @window.event def on_draw(): window.clear() batch.draw() @window2.event def on_draw(): window2.clear() batch2.draw() @window.event def on_mouse_press(x,y,button, modifier): window2.set_visible(True) pyglet.app.run()
修复说明
- 给第二个窗口单独添加
on_draw事件处理器,让每个窗口独立完成自身的清除和绘制操作。 - 移除第一个窗口
on_draw中对window2.clear()的调用,避免干扰第二个窗口的绘制流程。 - 鼠标点击事件只负责显示第二个窗口,绘制工作交给
on_draw事件处理,这样每次窗口需要刷新时,都会自动触发绘制逻辑,确保图形稳定显示。
内容的提问来源于stack exchange,提问作者bmgrice
相关产品推荐
相关产品推荐

