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