我正在尝试使用wxPython创建一个小工具。基本上,我希望我的代码从csv文件导入数据并打印个人的姓名和职业。无论如何,我在search_ppl定义中使用find_names函数时遇到错误。错误说明NameError:未定义全局名称'find_names'。我不明白如何解决它。如果我将函数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()
答案 0 :(得分:0)
更改行
find_names(key_index, results, info, employee_name)
到
results, info = self.find_names(key_index, results, info, employee_name)
因为您正在调用类方法,所以您需要使用self。在方法名称之前
您还需要为key_index,results&设置值。调用find_names之前的信息