global variable in main not getting recognised in another function in python

瘦欲@ 提交于 2019-12-25 05:24:13

问题


code below creates a layout and displays some text in the layout. Next the layout is displayed on the console screen using raw display module from urwid library. However running the code fails as a global variable ui, declared in main, is not recognised in another function.

Error code on running is :
Traceback (most recent call last):
File "./yamlUrwidUIPhase6.py", line 97, in <module>
main() File "./yamlUrwidUIPhase6.py", line 90, in main
form = FormDisplay() File "./yamlUrwidUIPhase6.py", line 23, in __init__
palette = ui.register_palette([
NameError: global name 'ui' is not defined

The code :

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

class FormDisplay(object):

    def __init__(self):
        self.ui = urwid.raw_display.Screen()
        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):
        #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():
    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()

I don't want to change the function formLayout as I intend to add more to this basic code framework, where in another function will be added that repeatedly calls formLayout to keep updating the screen based on reading values from a yml file.


回答1:


Writing global ui in main does nothing except make it so that main itself can write to a global variable called ui. If you want to write to that global variable from other functions (like your __init__), you need to include a global declaration there too. Every function where you want to assign to a global variable has to have its own global declaration.




回答2:


okay, thanks to people for various suggestions that helped me learn about the global scoping. I followed the answer by Jeff Shannon here : Using global variables in a function other than the one that created them seem to be able to get rid of the name scoping error caused by using global ui. here is what i did i used ui=urwid.raw_display.Screen() right after the imports and then declared global ui in the functions that used it. But now I get a different kind of error. Think it best to start a new question with the error now obtained.



来源:https://stackoverflow.com/questions/17901909/global-variable-in-main-not-getting-recognised-in-another-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!