Skip to main content
 首页 » 编程设计

python之如何使 Pyglet 的 ScrollableTextLayout 中的文本向上滚动,而不是向下滚动 .view_y 似乎没有文档中列出的效果

2025年05月04日13落叶

我正在尝试弄清楚如何在 Pyglet 的 ScrollableTextLayout 中使文本向上滚动,而不是向下滚动。为了清楚起见,这里有一个快速快照来显示我所说的“向上”的意思。 (以防万一)

我希望它如何表现:

根据文档,可以通过 view_y 属性实现此行为,但我尝试了各种不同的值,但都没有明显的变化。

代码:

import pyglet 
 
class LoadDialog(pyglet.sprite.Sprite): 
    def __init__(self): 
        self.lbatch = pyglet.graphics.Batch() 
 
        self.loading_window = pyglet.image.load('..\\resources\\loading_base.png') 
        super(LoadDialog, self).__init__(self.loading_window, batch=self.lbatch) 
 
 
        self.doc = pyglet.text.decode_text('Hello world!'.ljust(40)) 
        self.doc.set_style(0,12, dict(font_name='Arial', font_size=12, 
                                    color=(0,0,0,255))) 
 
        self.layout = pyglet.text.layout.ScrollableTextLayout(self.doc,  
                                            width=self.load_animation.width,  
                                            height=100, multiline=True, batch=self.lbatch) 
        self.layout.x = 220 
        self.layout.y = 160 
        self.layout.view_y = -80 
 
    def update(self, dx): 
        self.doc.insert_text(0, "New line".ljust(40)) 
 
 
 
 
 
 
sprite = LoadDialog() 
window = pyglet.window.Window(width=640, height=480) 
 
pyglet.gl.glClearColor(1, 1, 1, 1) 
 
@window.event 
def on_draw(): 
    window.clear() 
    sprite.lbatch.draw() 
    sprite.layout.draw() 
 
@window.event 
def update(dx): 
    sprite.update(dx) 
 
pyglet.clock.schedule_interval(update, 1.0) 
pyglet.app.run() 

我已经为 layout.view_y 尝试了很多值,从 -1 到荒谬的值,如 -3000 或 500 只是为了查看某些 是否发生了变化。但它总是给出如第一张图片所示的确切行为。

我做错了什么?

请您参考如下方法:

首先,您的示例取决于一个图像文件及其宽度(未提供),这会使测试稍微复杂一些。

其次,您正在创建一个 UnformattedDocument调用pyglet.text.decode_text , 然后你重复插入文本到 UnformattedDocument明确地在此行的位置 0(开始):

def update(self, dx): 
    self.doc.insert_text(0, "New line".ljust(40)) 

如果您希望文本出现在末尾,就像您在图形中暗示的那样,请将其插入末尾!

def update(self, dx): 
    # Fix the implied bug 
    self.doc.insert_text(-1, "New line".ljust(40)) 

第三,让我们回答您实际提出的问题。如果您阅读属性的 API 文档 ScrollableTextLayout.view_y你会发现……

Values outside of the range [height - content_height, 0] are automatically clipped in range.

...因此当 content_height 为 0 时将 view_y 设置为 -80,会导致 view_y 被裁剪为 0,然后您再也不会尝试设置 view_y。滚动问题的解决方案是每次内容高度更改时设置 view_y。对于一个简单的修复,您可以简单地设置 view_y,这样您的内容的底部将始终向上滚动到框架的底部:

def update(self, dx): 
    # Fix the implied bug 
    self.doc.insert_text(-1, "New line".ljust(40)) 
    # The answer to the stated question 
    self.layout.view_y = -self.layout.content_height