Python-Pyglet使用外部字体作为标签

2024-10-03 06:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个项目,目前,我一直试图改变字体的标签在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)

Tags: 项目图书馆batch字体标签ttfwindowwidth
1条回答
网友
1楼 · 发布于 2024-10-03 06:26:55

所以这个错误很简单。加载的字体名不是ZukaDoodle,而是带有空格的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将是最大值。你知道吗

相关问题 更多 >