-2

我正在尝试开发一个非常简单的 wxpython GUI。目前只有一个按钮可以打开一个文件对话框,并在其下方有一个文本控制框。目前我要做的就是将打开的文件名打印到文本控制框,但不断收到错误消息。“未定义全局名称”。任何帮助,将不胜感激!

#!/usr/bin/python

import os
import wx
import wx.lib.agw.multidirdialog as MDD

wildcard = "Python source (*.py)|*.py|" \
            "All files (*.*)|*.*"

########################################################################
class MyFrame(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY)
        panel = wx.Panel(self, wx.ID_ANY)
        self.currentDirectory = os.getcwd()

        text = wx.TextCtrl(panel, -1, "",style=wx.TE_MULTILINE|wx.HSCROLL)

        # create the buttons and bindings
        openFileDlgBtn = wx.Button(panel, label="Show OPEN FileDialog")
        openFileDlgBtn.Bind(wx.EVT_BUTTON, self.onOpenFile)

        # put the buttons in a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(openFileDlgBtn, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(text, 1, wx.EXPAND|wx.ALL, 5)
        panel.SetSizer(sizer)

    #----------------------------------------------------------------------
    def onOpenFile(self, event):
        """
        Create and show the Open FileDialog
        """
        dlg = wx.FileDialog(
            self, message="Choose a file",
            defaultDir=self.currentDirectory, 
            defaultFile="",
            wildcard=wildcard,
            style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
            )
        if dlg.ShowModal() == wx.ID_OK:
            paths = dlg.GetPaths()
            print "You chose the following file(s):"
            for path in paths:
                print path
                text.AppendText('path') 
        dlg.Destroy()

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    frame.Show()
    app.MainLoop()
4

1 回答 1

2

这是一个有根据的猜测,仅基于观察您的代码:

text您在方法中引用onOpenFile(),但不要在该方法中定义它。text是不同方法中的本地名称。

如果您想访问您在方法中TextCtrl分配给的对象,请存储对它的引用,以便您也可以在其他方法中引用它:text__init__self

def __init__(self):
    # ....
    self.text = text = wx.TextCtrl(panel, -1, "",style=wx.TE_MULTILINE|wx.HSCROLL)

def onOpenFile(self, event):
    # ....
    if dlg.ShowModal() == wx.ID_OK:
        paths = dlg.GetPaths()
        print "You chose the following file(s):"
        for path in paths:
            print path
            self.text.AppendText('path') 
于 2013-07-20T12:45:26.943 回答