簡體   English   中英

如何通過on_button_press事件運行pyglet.window.clear函數?

[英]How do I run the pyglet.window.clear function through a on_button_press event?

長話短說,我正在使用Pyglet在python 3中制作基於文本的游戲,但無法清除窗口。 我想清除所有內容,以便可以輸入新單詞和新圖片。我希望這樣設置:

@window.event
def on_key_press(key.escape,modifier)
    window.clear

或類似的東西,但似乎不起作用。 有人有什么建議,想法嗎? 唯一的其他想法是將單詞轉換為黑色,將任何圖像轉換為黑色,然后將其分層,但是窗口仍將加載該東西,隨着游戲的進行,我可以看到它開始消耗越來越多的RAM來運行帶有所有先前圖片和文字的窗口。

我寧願避免這種情況,只是將其清除,然后,我也不必一遍又一遍地將相同的代碼復制為黑色。

謝謝,本

import pyglet
from pyglet.gl import *

from time import time # Used for FPS calc

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self):
        super(main, self).__init__(800, 800, fullscreen = False, vsync = True)

        self.running = True

        self.fps_counter = 0
        self.last_fps = time()
        self.fps_text = pyglet.text.Label(str(self.fps_counter), font_size=12, x=10, y=10)

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.running = False
        else:
            self.clear() # However, this is done in the render() logic anyway.

    def on_draw(self):
        self.render()

    def render(self):
        self.clear()

        # And flip the GL buffer
        self.fps_counter += 1
        if time() - self.last_fps > 1:
            self.fps_text.text = str(self.fps_counter)
            self.fps_counter = 0
            self.last_fps = time()

        self.fps_text.draw()

        self.flip()

    def run(self):
        while self.running is True:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()
            if event and event.type == pygame.QUIT:
                self.running = False

x = main()
x.run()

這是針對黑屏的FPS計數器的快速,骯臟的復制和粘貼邏輯。
每次按鍵都會強制清除屏幕。

在您的示例中,您可能將pyglet.window.Window()存儲為myWindow = py...或類似的東西。 然后在該全局變量上,從裝飾器調用myWindow.clear()

import pyglet
myWindow = pyglet.window.Window()

@myWindow.event
def on_key_press(symbol, modifier):
    myWindow.clear()

pyglet.all.run()

(您最后沒有一個:key.escape應該只是一個變量,而clear是一個函數而不是變量。)

但是,如果您要繼續編寫大型圖形應用程序,我強烈建議您對代碼進行分類,並立即將其設置為“ OOP”,否則圖形庫往往會變得相當混亂。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM