2012-10-24 55 views
0

由於標題暗示我想要從一個列表框中選擇項目,請按下按鈕並將其添加到第二個列表框。使用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

這個代碼嵌套到類中嗎?全局變量和成員方法之間有一種奇怪的混合。我認爲你應該重構:刪除全局變量並把所有東西都放到一個類中 – luc

+0

是的,它在一個類中。我將重新發布整個班級 – user1104854

+0

如果您意識到代碼需要被標記,您爲什麼不這樣做?以您所提問題的質量爲榮。 –

回答

1

這是相當困難的遵循代碼 - 例如,其中self.fileListSorted定義? - 你有一個全局的fileListSorted和一個實例變量self.fileListSorted,它們是不同的東西。但是,你似乎是讓他們混淆(例如,爲什麼會出現一行

global fileListSorted 

moveFile當你從來沒有在那裏使用fileListSorted?)還要注意項目添加到ListBox,您通常使用insert方法,你還沒有在moveFiles中使用,就像你已經顯示的那樣...

+0

我嘗試使用插入(結束,...),但我得到一個錯誤,說必須有一個整數。 – user1104854

+0

對不起,我還是一個初學者,特別是當涉及到python的OOP。我將self.fileListSorted更改爲fileLIst,它工作。 – user1104854

+0

@ user1104854 - 沒問題。很高興幫助。 :)。繼續學習python - 這是一個非常強大的語言。 – mgilson

相關問題