繁体   English   中英

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

[英]Adding items from one listbox to another with 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

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

global fileListSorted

当您从未在其中使用fileListSorted时是否在moveFile中?)还请注意,要将项目添加到ListBox ,通常使用insert方法,就您所显示的而言,您尚未在moveFiles使用该方法...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM