python - 尝试使用 urwid 创建控制台屏幕时出现“断言错误”

标签 python user-interface python-2.7 console-application urwid

下面的代码创建一个布局并在布局中显示一些文本。接下来,使用 urwid 库中的原始显示模块将布局显示在控制台屏幕上。 (有关我的完整项目的更多信息可以从 widget advice for a console projecturwid for a console project 的问题中收集到。我的 Skype 帮助请求是 here。)但是运行代码失败,因为引发了断言错误,如下所述:

运行代码的错误是:
Traceback (most recent call last):<br/> File "./yamlUrwidUIPhase6.py", line 98, in <module><br/> main()<br/> File "./yamlUrwidUIPhase6.py", line 92, in main<br/> form.main()<br/> File "./yamlUrwidUIPhase6.py", line 48, in main<br/> self.view = formLayout()<br/> File "./yamlUrwidUIPhase6.py", line 77, in formLayout<br/> ui.draw_screen(dim, frame.render(dim, True))<br/> File "/usr/lib64/python2.7/site-packages/urwid/raw_display.py", line 535, in draw_screen<br/> assert self._started<br/> AssertionError

代码:

import sys  
sys.path.append('./lib')  
import os  
from pprint import pprint  
import random  
import urwid  
ui=urwid.raw_display.Screen()


class FormDisplay(object):

    def __init__(self):
        global ui
        self.ui = ui
        palette = ui.register_palette([
            ('Field', 'dark green, bold', 'black'), # information fields, Search: etc.
            ('Info', 'dark green', 'black'), # information in fields
            ('Bg', 'black', 'black'), # screen background
            ('InfoFooterText', 'white', 'dark blue'), # footer text
            ('InfoFooterHotkey', 'dark cyan, bold', 'dark blue'), # hotkeys in footer text
            ('InfoFooter', 'black', 'dark blue'),  # footer background
            ('InfoHeaderText', 'white, bold', 'dark blue'), # header text
            ('InfoHeader', 'black', 'dark blue'), # header background
            ('BigText', RandomColor(), 'black'), # main menu banner text
            ('GeneralInfo', 'brown', 'black'), # main menu text
            ('LastModifiedField', 'dark cyan, bold', 'black'), # Last modified:
            ('LastModifiedDate', 'dark cyan', 'black'), # info in Last modified:
            ('PopupMessageText', 'black', 'dark cyan'), # popup message text
            ('PopupMessageBg', 'black', 'dark cyan'), # popup message background
            ('SearchBoxHeaderText', 'light gray, bold', 'dark cyan'), # field names in the search box
            ('SearchBoxHeaderBg', 'black', 'dark cyan'), # field name background in the search box
            ('OnFocusBg', 'white', 'dark magenta') # background when a widget is focused
           ])
        urwid.set_encoding('utf8')

    def main(self):
        global ui
        #self.view = ui.run_wrapper(formLayout)
        self.view = formLayout()
        self.ui.start()
        self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_input)
        self.loop.run()

    def unhandled_input(self, key):
        if key == 'f8':
          quit()
          return


def formLayout():
    global ui
    text1 = urwid.Text("Urwid 3DS Application program - F8 exits.")
    text2 = urwid.Text("One mission accomplished")

    textH = urwid.Text("topmost Pile text")
    cols = urwid.Columns([text1,text2])
    pile = urwid.Pile([textH,cols])
    fill = urwid.Filler(pile)

    textT  = urwid.Text("Display") 

    textSH = urwid.Text("Pile text in Frame")
    textF = urwid.Text("Good progress !")

    frame = urwid.Frame(fill,header=urwid.Pile([textT,textSH]),footer=textF)
    dim = ui.get_cols_rows()

    ui.draw_screen(dim, frame.render(dim, True))
    return

def RandomColor():
    '''Pick a random color for the main menu text'''
    listOfColors = ['dark red', 'dark green', 'brown', 'dark blue',
                    'dark magenta', 'dark cyan', 'light gray',
                    'dark gray', 'light red', 'light green', 'yellow',
                    'light blue', 'light magenta', 'light cyan', 'default']
    color = listOfColors[random.randint(0, 14)]
    return color

def main():
    form = FormDisplay()
    form.main()

########################################
##### MAIN ENTRY POINT
########################################
if __name__ == '__main__':
    main()

我不想更改函数 formLayout,因为我打算向这个基本代码框架添加更多内容,其中将添加另一个函数,该函数重复调用 formLayout 以根据从 yml 文件读取的值不断更新屏幕。我已经有一个单独的代码来处理读取 yaml 文件并从中提取有序字典。在弄清楚如何让基本的 urwid 控制台正常工作之后,我可以继续集成两者以创建我的最终应用程序。

最佳答案

这意味着 self._started 已被评估为 False。

assert <Some boolean expression>, "Message if exp is False"

如果表达式被评估为 True,则不会发生任何特殊情况,但如果表达式被评估为 False,则会抛出 AssertionError 异常。

如果您想要更清晰的消息,您可以尝试/排除该行:

try:
    assert self._started, "The screen is not up and running !"
except AssertionError as e:
    print "Oops, something happened: " + str(e)

一些文档:http://www.tutorialspoint.com/python/assertions_in_python.htm

关于python - 尝试使用 urwid 创建控制台屏幕时出现“断言错误”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17903820/

相关文章:

python - 如何使 python 3.6 导入文件相对于文件位置?

reactjs - 如何使用 Material ui 处理快速拨号操作?

java - 在 Windows 任务栏中创建多个图标

python - Python 2.7 中有什么类似于 Go 的 `time.Tick` 或 Netty 的 `HashedWheelTimer` 吗?

python - 在python类中实现树的递归函数

python - 从 python 正则表达式中提取两个值

python - 如何在 ipython 的命名空间中重新加载对象

user-interface - 当我构建时,qtcreator 并不总是刷新我的用户界面

python - 修改数据框单元格中的字典

python - 在没有嵌套循环的情况下访问字典的嵌套级别