Python Pyglet 为标签使用外部字体

Python Pyglet Using External Fonts For Labels

我目前正在做一个项目,我一直在尝试将 pyglet 库中的标签字体更改为我在网上找到的字体,但我无法让它工作。我现在尝试在线搜索一个小时,但似乎没有任何效果。添加了一些代码以供参考:

font.add_file('ZukaDoodle.ttf')
ZukaDoodle = font.load('ZukaDoodle.ttf', 16)

PlayLabel = pyglet.text.Label('Go', font_name='ZukaDoodle', font_size=100, x=window.width // 2,
                          y=window.height - 450, anchor_x='center', anchor_y='center', 
                                 batch=buttons_batch,
                                      color=(0, 0, 0, 1000), width=250, height=130)

所以错误很简单。加载的字体名称不是 ZukaDoodle,而是带有 space 的 Zuka Doodle。这是一个有效的可执行示例:

from pyglet import *
from pyglet.gl import *

font.add_file('ZukaDoodle.ttf')
ZukaDoodle = font.load('ZukaDoodle.ttf', 16)

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)
        self.x, self.y = 0, 0

        self.keys = {}

        self.mouse_x = 0
        self.mouse_y = 0

        self.PlayLabel = pyglet.text.Label('Go', font_name='Zuka Doodle', font_size=100,
                                            x=self.width // 2,
                                            y=self.height - 450,
                                            anchor_x='center', anchor_y='center', 
                                            color=(255, 0, 0, 255),
                                            width=250, height=130)

        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_mouse_motion(self, x, y, dx, dy):
        self.mouse_x = x

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        self.keys[symbol] = True

    def render(self):
        self.clear()

        self.PlayLabel.draw()

        ## Add stuff you want to render here.
        ## Preferably in the form of a batch.

        self.flip()

    def run(self):
        while self.alive == 1:
            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 __name__ == '__main__':
    x = main()
    x.run()

这里的主要区别是font_name='Zuka Doodle'
此外,alpha 通道通常不需要高于 255,因为这是彩色字节的最大值,因此除非您对每个通道使用 16 位颜色表示,否则 255 将是最大值。