在另一个函数中调用函数的局部变量

时间:2013-02-18 07:31:21

标签: python-2.7

我在python中创建了一个设置窗口,其中我有一些路径设置,必须是一次设置。这是示例演示代码,

import wx
import os
class SettingWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)
        panel= wx.Panel(self,-1)
        font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD)
        field1 = wx.TextCtrl(panel,pos=(120,25),size=(170,20))
        vsizer = wx.BoxSizer(wx.VERTICAL)
        field1_sz=wx.BoxSizer(wx.HORIZONTAL)
        field2_sz=wx.BoxSizer(wx.HORIZONTAL)
        field1_lbl=wx.StaticText(panel,-1, label='Repo URL path:', pos=(25, 25))
        field1_lbl.SetFont(font)
        field1_sz.AddSpacer(50)
        field1_sz.Add(field1_lbl)
        field1_sz.AddSpacer(5) # put 5px of space between
        field1_sz.Add(field1)
        field1_sz.AddSpacer(50)

        vsizer.AddSpacer(50)
        vsizer.Add(field1_sz)
        vsizer.AddSpacer(15)
        vsizer.Add(field2_sz)
        vsizer.AddSpacer(50)

        btn1 = wx.Button(panel, label='Browse',pos=(300,25),size=(60,20))
        btn1.Bind(wx.EVT_BUTTON, self.opendir)

    def opendir(self, event):
        dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        if dlg.ShowModal() == wx.ID_OK:
            field1.SetValue("%s",dlg.GetPath())

        dlg.Destroy()




class MyApp(wx.App):
    def OnInit(self):
        frame= SettingWindow(None,-1,'Setting Window')
        frame.Show()
        self.SetTopWindow(frame)
        return True
app= MyApp(0)
app.MainLoop()

我想在textCtrl中显示我从opendir获得的路径。我发现如下错误, Traceback(最近一次调用最后一次):   文件“D:\ PROJECT \ SettingWindow.py”,第58行,在opendir中     return(field1) NameError:未定义全局名称“field1”

2 个答案:

答案 0 :(得分:1)

使用self.field1而不是变量field1:

self.field1 = wx.TextCtrl(panel,pos=(120,25),size=(170,20))

self.field1.SetValue(dlg.GetPath())

答案 1 :(得分:1)

此代码用于在单击复选框

时隐藏TextCtrl字段
def OnCheckBox(self,event):
    if self.checkbox.Value==False:
        self.field.Enable(True)
    else:
        self.field.Enable(False)