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

时间:2013-07-28 00:28:28

标签: 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):
File "./yamlUrwidUIPhase6.py", line 98, in <module>
main()
File "./yamlUrwidUIPhase6.py", line 92, in main
form.main()
File "./yamlUrwidUIPhase6.py", line 48, in main
self.view = formLayout()
File "./yamlUrwidUIPhase6.py", line 77, in formLayout
ui.draw_screen(dim, frame.render(dim, True))
File "/usr/lib64/python2.7/site-packages/urwid/raw_display.py", line 535, in draw_screen
assert self._started
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控制台工作之后,我可以继续集成两者来创建我的最终应用程序。

2 个答案:

答案 0 :(得分:3)

这意味着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

答案 1 :(得分:2)

您在屏幕formLayout之前致电startformLayout调用ui.draw_screen,这需要屏幕已启动。