我正在尝试使用 wxPython 创建一个小工具。基本上,我希望我的代码从 csv 文件导入数据并打印个人的姓名和职业。无论如何,在 search_ppl 定义中使用 find_names 函数时出现错误。错误显示 NameError: global name 'find_names' is not defined。我不明白如何解决它。如果我将函数 find_names 设为全局,则代码也不起作用。我已经在 python 中为此编写了一个工作代码,其中结果被写入终端窗口。但是 wxPython 对我来说还是个新手,我还不太明白……谢谢你的帮助!
#!/usr/bin/env python
import wx
import wx.lib.mixins.listctrl as listmix
import csv
from wxPython.wx import *
info = csv.reader(open('data.csv', 'rb'),delimiter=',')
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
"Search", pos=(920,730), size=(350,250) )
panel = wx.Panel(self, wx.ID_ANY)
self.control = wxTextCtrl(panel, 1, style=wxTE_PROCESS_ENTER
, pos=(130,180), size=(200,28))
self.list_ctrl = wx.ListCtrl(panel
, style=wx.LC_REPORT|wx.BORDER_SUNKEN
, size=(350,170))
self.list_ctrl.InsertColumn(0, "Name", width = 120)
self.list_ctrl.InsertColumn(1, "Occupation", width = 220)
index = 0
for row in info:
self.list_ctrl.InsertStringItem(index, row[1])
self.list_ctrl.SetStringItem(index, 1, row[4])
if index % 2:
self.list_ctrl.SetItemBackgroundColour(index, "white")
else:
self.list_ctrl.SetItemBackgroundColour(index, "yellow")
index += 1
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list_ctrl, 0, wx.ALL|wx.CENTER, 5)
panel.SetSizer(sizer)
btn = wx.Button(panel, label="Search", pos=(20,180))
btn.Bind(wx.EVT_BUTTON, self.search_ppl)
key_index = 4
results = []
def search_ppl(self, event):
employee_name = self.control.GetValue()
find_names(key_index, results, info, employee_name)
print results
def find_names(key_index, results, info, employee_name):
for row in info: #search each row in data.csv
if employee_name in row[key_index]: #name is in file results.append(row[1]) #add element to the list
return results, info
if __name__ == '__main__':
app = wx.App(False)
frame = MyFrame()
frame.Show()
app.MainLoop()