使用tkinter从python中的不同函数调用listbox

时间:2012-10-24 18:10:29

标签: python oop user-interface object tkinter

我正在尝试添加和删除列表框中的项目但是我收到以下错误:

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 []

1 个答案:

答案 0 :(得分: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)

fileList我是一个小部件,每个Tkinter小部件都使用dictionnary表示法来表示属性(例如self.fileList['background'])。

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