将变量传递给对话框

时间:2012-06-27 11:19:03

标签: python gtk python-2.7 pygtk canonical-quickly

我需要将消息传递给错误对话框,以便将其显示给用户。

首次尝试

PreferencesDialog.py

dlgError = ErrorDialog ('Have you been messing with the configuration files?')
dlgError.run ()

ErrorDialog.py

global message = None

def __new__(cls, msg):
    builder = get_builder('ErrorDialog')
    new_object = builder.get_object('error_dialog')
    new_object.finish_initializing(builder)

    global message
    message = msg

    return new_object

def finish_initializing(self, builder):

    # Get a reference to the builder and set up the signals.
    self.builder = builder
    self.ui = builder.get_ui(self)

    global message
    self.builder.get_object ('lblMessage').set_text (message)

第二次尝试

PreferencesDialog.py

dlgError = ErrorDialog ()
dlgError.message = 'Have you been messing with the configuration files?'
dlgError.run ()

ErrorDialog.py

global message = None

def __new__(cls):
    builder = get_builder('ErrorDialog')
    new_object = builder.get_object('error_dialog')
    new_object.finish_initializing(builder)

    return new_object

def finish_initializing(self, builder):

    # Get a reference to the builder and set up the signals.
    self.builder = builder
    self.ui = builder.get_ui(self)

    global message
    self.builder.get_object ('lblMessage').set_text (message)

两者都抛出相同的异常;

self.builder.get_object ('lblMessage').set_text (message)
NameError: global name 'message' is not defined

请协助。我正在使用Quickly,GTK 3和Python 2.7。

2 个答案:

答案 0 :(得分:1)

为什么不通过在message中设置__init__成为类实例的成员?

def __init__(self, msg):
  self._message = msg

def finish_initializing(self, builder):
  self.builder.get_object("lblMessage").set_text(self._message)

答案 1 :(得分:0)

我设置了一个对话框,我在对话框中传递了一个变量,将文本放入输入框中。诀窍是将变量传递给 new ,然后调用finish.initializing()时将其放入其中。这是代码:

class QuerynameDialog(Gtk.Dialog):
    __gtype_name__ = "QuerynameDialog"

    def __new__(cls, name):
        """Special static method that's automatically called by Python when 
        constructing a new instance of this class.

        Returns a fully instantiated QuerynameDialog object.
        """
        builder = get_builder('QuerynameDialog')
        new_object = builder.get_object('queryname_dialog')
        new_object.finish_initializing(builder,name)
        return new_object


    def finish_initializing(self, builder,name):
        """Called when we're finished initializing.

        finish_initalizing should be called after parsing the ui definition
        and creating a QuerynameDialog object with it in order to
        finish initializing the start of the new QuerynameDialog
        instance.
        """
        # Get a reference to the builder and set up the signals.
        self.builder = builder
        self.ui = builder.get_ui(self)
        self.builder.get_object('name_entry').set_text(name)