python - 类型错误:不支持的操作数类型

标签 python pyglet typeerror

这是我正在编写的程序,应该在窗口中显示一些文本...

import pyglet
from pyglet import window
from pyglet.text.layout import TextLayout

class Window(pyglet.window.Window):
    def __init__(self):
        super(Window, self).__init__(width = 800, height = 600,
                                 caption = "Prototype")

        self.disclaimer = pyglet.text.Label("Hello World",
                                   font_name = 'Times New Roman',
                                   font_size=36,
                                   color = (255, 255, 255, 255),
                                   x = TextLayout.width / 2,
                                   y = TextLayout.height / 2,
                                   anchor_x='center', anchor_y='center')

def on_draw(self):
    self.clear()
    self.disclaimer.draw()

if __name__ == '__main__':
    window = Window()
    pyglet.app.run()

...但是每次我尝试运行它时都会出现此错误

line 16
x = TextLayout.width / 2,
TypeError: unsupported operand type(s) for /: 'property' and 'int'

我很确定这意味着我试图划分一个字符串,但在 Pyglet 文档中它说宽度和高度是整数。我不知道我做错了什么。

最佳答案

TextLayout 是一个——所以TextLayout.width 是一个原始属性,对您来说毫无用处;您希望从 TextLayout 类的实例 获取宽度,而不是从类本身获取!此外,该类专门用于布置文本文档,所以我真的不明白您为什么要获取它(因为您周围没有文档对象)。

我怀疑你真正想要的是:

                               x = self.width / 2,
                               y = self.height / 2,

并删除 TextLayout 的导入和所有提及。

关于python - 类型错误:不支持的操作数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3126436/

相关文章:

python - 使用 Python 将列表导出为 CSV

python - 使用 python (pandas) 对 CSV 文件进行条件合并

python - 函数内的函数,用于根据列值迭代每行

python - Pyglet无限循环播放音频

python - 如何在 pymunk 中更改形状的颜色?

Python Cocos2d : tiles show up only once

Python 打印错误 : %d format: a number is required, 不是元组

python - MySQL:如果不重新打开 shell,Django .create 后跟 .get 将无法工作

Python 类型错误 : 'list' object cannot be interpreted as an integer

python - 在 python 中使用 .append 定义列表