这个例子无法运行,因为调用 pyglet.clock.schedule_interval 的作用域中没有变量 pick
你的意图不太清楚。你真的希望每次运行程序时,间隔都不一样吗?固定间隔似乎更合理。
调整一下结构也许有用。
运行时行为有点奇怪,不过可能只是 pyglet 的特点,也可能是我理解不够。无论如何,这个版本会以伪随机的频率交替显示 "Press A" 和 "Press B"。
from random import SystemRandom
from pyglet import window, text, clock, app
# pylint: disable=possibly-used-before-assignment,unused-argument
# note use of variable names in uppercase denoting global scope
TICK_SECONDS = 3.
def refresh(elapsed: float) -> None:
SCREEN.clear()
RNG.choice(CAPTIONS).draw()
if __name__ == "__main__":
SCREEN = window.Window(fullscreen=True)
label_options = { # these parameters are common to both captions
"font_name": "Times New Roman",
"font_size": 72,
"x": SCREEN.width // 2,
"y": SCREEN.height // 2,
"anchor_x": "center",
"anchor_y": "center",
}
# create a tuple of the 2 captions
CAPTIONS = text.Label("Press A", **label_options), text.Label("Press B", **label_options)
RNG = SystemRandom() # only do this once
clock.schedule_interval(refresh, TICK_SECONDS)
app.run()
从英语翻译·查看原文This example won't run since the variable pick isn't in the scope containing the invocation of pyglet.clock.schedule_interval
What you intend isn't clear. Should the interval really differ from one execution of this program to another? Keeping the interval constant seems more reasonable.
Reorganizing things could help.
The runtime behavior seems a little strange, although that could simply be something about pyglet or my limited understanding of it. Regardless, this alternates between showing "Press A" and "Press B" at a pseudo-random rate.
from random import SystemRandom
from pyglet import window, text, clock, app
# pylint: disable=possibly-used-before-assignment,unused-argument
# note use of variable names in uppercase denoting global scope
TICK_SECONDS = 3.
def refresh(elapsed: float) -> None:
SCREEN.clear()
RNG.choice(CAPTIONS).draw()
if __name__ == "__main__":
SCREEN = window.Window(fullscreen=True)
label_options = { # these parameters are common to both captions
"font_name": "Times New Roman",
"font_size": 72,
"x": SCREEN.width // 2,
"y": SCREEN.height // 2,
"anchor_x": "center",
"anchor_y": "center",
}
# create a tuple of the 2 captions
CAPTIONS = text.Label("Press A", **label_options), text.Label("Press B", **label_options)
RNG = SystemRandom() # only do this once
clock.schedule_interval(refresh, TICK_SECONDS)
app.run()