0

我正在尝试从列表框中添加和删除项目,但出现以下错误:

files = self.fileList()
TypeError: 'list' object is not callable

如果我不能调用它,我如何访问这个列表?我试图将它用作全局变量,但也许我使用不正确。我希望能够从该列表框中获取项目,并在按下按钮时将它们添加到另一个列表框中。

class Actions:

def openfile(self): #select a directory to view files
    directory = tkFileDialog.askdirectory(initialdir='.')
    self.directoryContents(directory)


def filename(self):
    Label (text='Please select a directory').pack(side=TOP,padx=10,pady=10)

files = []
fileListSorted = []
fileList = []

#display the contents of the directory
def directoryContents(self, directory): #displays two listBoxes containing items
    scrollbar = Scrollbar() #left scrollbar - display contents in directory
    scrollbar.pack(side = LEFT, fill = Y) 

    scrollbarSorted = Scrollbar() #right scrollbar - display sorted files 
    scrollbarSorted.pack(side = RIGHT, fill = Y)

    #files displayed in the left listBox
    global fileList
    fileList = Listbox(yscrollcommand = scrollbar.set) 
    for filename in os.listdir(directory):
        fileList.insert(END, filename)
    fileList.pack(side =LEFT, fill = BOTH)
    scrollbar.config(command = fileList.yview)


    global fileListSorted #this is for the filelist in the right window. contains the values the user has selected
    fileListSorted = Listbox(yscrollcommand = scrollbarSorted.set) #second listbox (button will send selected files to this window)
    fileListSorted.pack(side=RIGHT, fill = BOTH)
    scrollbarSorted.config(command = fileListSorted.yview)

    selection = fileList.curselection() #select the file
    b = Button(text="->", command=lambda:self.moveFile(fileList.curselection()))#send the file to moveFile to be added to fileListSorted
    b.pack(pady=5, padx =20)


def moveFile(self,File):
    files = self.fileList()
    insertValue = int(File[0]) #convert the item to integer
    insertName = self.fileList[insertValue] #get the name of the file to be inserted
    fileListSorted.insert(END,str(insertName)) #insertthe value to the fileList array

我将文件更改为以下内容以查看文件是否设置正确并返回一个空数组

files = self.fileList
print files
#prints []
4

1 回答 1

1

你从不初始化self.fileList(也不fileListSorted)。当你写directoryContents

global fileList
fileList = Listbox(yscrollcommand = scrollbar.set)
...

您在一个名为fileList. 您可以在任何self.fileList地方使用(或添加global fileList所有功能,然后使用fileList)。

但是,我对您对类的使用持怀疑态度,您应该尝试理解面向对象的概念及其在 python 中的实现,或者暂时忽略这些概念。


编辑

我已尝试运行您的代码,您也可能会更改该行

insertName = self.fileList[insertValue]

经过

insertName = self.fileList.get(insertValue)

fileListia 小部件和每个 Tkinter 小部件都使用字典表示法来表示属性(例如self.fileList['background'])。

请注意,获取一个数字或一个包含数字的字符串,因此您在上面一行的转换是无用的。另请注意,您可以通过get(0,END).

于 2012-10-24T18:37:48.500 回答