使用tkinter将项目从一个列表框添加到另一个列表框

时间:2012-10-24 11:26:13

标签: python user-interface listbox tkinter

由于标题暗示我正在尝试从一个列表框中选择项目,请按一个按钮,然后将其添加到第二个列表框中。

当我单击按钮移动时,该值将在命令提示符下打印,但列表框本身不会更新。

我复制并粘贴了所以我意识到一切都应该在一个地方标记。

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

#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, padx = 2, pady=100)

    fileList = Listbox(yscrollcommand = scrollbar.set) #files displayed in the left listBox
    for filename in os.listdir(directory):
        fileList.insert(END, filename)
        global files 
        self.files.append(filename) #insert the values into the files array so we know which element we want to enter in moveFile
    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)


##moveFile addes files to the array fileLIst2, which is the fileList on the right
def moveFile(self,File):
    insertValue = int(File[0]) #convert the item to integer
    global files
    insertName = self.files[insertValue] #get the name of the file to be inserted

    global fileListSorted
    self.fileListSorted.append(str(insertName)) #append the value to the fileList array
    print self.fileListSorted #second listbox list

1 个答案:

答案 0 :(得分:1)

遵循该代码非常困难 - 例如,self.fileListSorted定义在哪里? - 您有一个全局fileListSorted和一个实例变量self.fileListSorted,它们是不同的东西。但是,你似乎让他们感到困惑(例如,为什么会有一行

global fileListSorted
如果您从未在moveFile使用fileListSorted,请在ListBox

另请注意,要将项目添加到insert,您通常会使用moveFiles方法至于你在{{1}}中的使用,无论如何......