gpt4 book ai didi

python-3.x - Pyglet hello world 示例在按下键之前不显示标签

转载 作者:行者123 更新时间:2023-12-04 18:46:22 26 4
gpt4 key购买 nike

import pyglet

window = pyglet.window.Window()
label = pyglet.text.Label("Hello World!",
font_name="Times New Roman",
color=(255,255,255,255),
font_size=36,
x=window.width//2, y=window.height//2,
anchor_x="center", anchor_y="center")

@window.event
def on_draw():
window.clear()
label.draw()

pyglet.app.run()
此代码取自 https://pyglet.readthedocs.io/en/pyglet-1.2-maintenance/programming_guide/quickstart.html 的 pyglet 教程但是在运行时它不会绘制标签,直到按下任何键。我添加了颜色,因为我认为文本可能默认为黑色。
关于为什么会发生这种行为,我是否遗漏了一些非常明显的东西?
好的,我的内存被评论搅动了,我安装了 MS 字体,它现在可以在 python 2.x 中运行,但我仍然需要按一个键才能查看 python 3 中的文本。也许字体是一个红鲱鱼并且与 python 3 有一些不兼容。

最佳答案

如评论中所述。
在 Internet 上找到的大多数示例(甚至大多数指南)都假定 Windows 平台。

如果有 font=使用 Windows 字体声明但您运行的是 Linux,请确保安装了正确的字体或恢复为已安装的字体。

$ fc-list

也不声明字体也可以:
label = pyglet.text.Label("Hello World!",
color=(255,255,255,255),
font_size=36,
x=window.width//2, y=window.height//2,
anchor_x="center", anchor_y="center")

因为 Pyglet 将默认为无衬线:

If you do not particularly care which font is used, and just need to display some readable text, you can specify None as the family name, which will load a default sans-serif font (Helvetica on Mac OS X, Arial on Windows XP)



您的问题可能是您在绘制某些内容后没有手动更新屏幕。通常当你按下一个键时,它会强制一个 window.flip() ,这基本上意味着更新屏幕内容。 window.clear()也会触发此行为,但 x.draw()才不是。为什么?好吧,计算机图形学中需要时间的并不是计算,而是将它们更新到屏幕上需要时间.. .draw()不更新屏幕,它只是将内容放在图形缓冲区(“页面”)中,您决定何时翻转页面并在屏幕上显示新缓冲区。

试试这个:
@window.event
def on_draw():
window.clear()
label.draw()
window.flip()

这可能是一个矫枉过正的解决方案,但它可能会解决问题。
这覆盖了 pyglet 的默认循环和默认绘制行为,它也是我在我的 pyglet 项目中使用最多的类之一,因为它让我可以选择创建自己的框架。
import pyglet

class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__(vsync = False)
self.sprites = {}
self.sprites['testlabel'] = label = pyglet.text.Label("Hello World!",
color=(255,255,255,255),
font_size=36,
x=self.width//2, y=self.height//2, #self here, being pyglet.window.Window that we've inherited and instanciated with super().
anchor_x="center", anchor_y="center")
self.alive = 1

def on_draw(self):
self.render()

def render(self):
self.clear()
for sprite_name, sprite_obj in self.sprites.items():
sprite_obj.draw()
self.flip()

def on_close(self):
self.alive = 0

def run(self):
while self.alive:
self.render()
# This is very important, this queries (and empties)
# the pyglet event queue, if this queue isn't cleared
# pyglet will hang because it can't input more events,
# and a full buffer is a bad buffer, so we **NEED** this!
event = self.dispatch_events()

win = Window()
win.run()

这是非常基本的,但您可以在 def render(self): 中添加更多 Sprite 、对象并渲染它们.

关于python-3.x - Pyglet hello world 示例在按下键之前不显示标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37354309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com