gpt4 book ai didi

python - Tkinter 列表框没有正确删除项目

转载 作者:太空宇宙 更新时间:2023-11-04 09:19:01 24 4
gpt4 key购买 nike

我有一个方法假设采用搜索参数并从列表中删除不符合该参数的所有内容。但是当它运行时,它几乎随机地删除了列表项。我调试了它,它正确地确定了是否需要删除一个项目,但它没有删除正确的项目。我认为这与当我删除一个项目时它弄乱了列表其余部分的索引有关,这与我跟踪索引的方法无关。我发布了整个类(class),但相关代码在底部

class StudentFinderWindow(Tkinter.Toplevel):

def __init__(self):
Tkinter.Toplevel.__init__(self) # Create Window

##### window attributes
self.title('Edit Students') #sets window title

##### puts stuff into the window

# text
editStudentInfoLabel = Tkinter.Label(self,text='Select the student from the list below or search for one in the search box provided')
editStudentInfoLabel.grid(row=0, column=0)

# entry box
self.searchRepositoryEntry = Tkinter.Entry(self)
self.searchRepositoryEntry.grid(row=1, column=0)

# list box
self.searchResults = Tkinter.Listbox(self)
self.searchResults.grid(row=2, column=0)


# search results initial updater
self.getStudentList()
for student in self.studentList:
self.searchResults.insert(Tkinter.END, student)

##### event handler

self.searchRepositoryEntry.bind('<KeyRelease>', self.updateSearch)

这是相关代码

    def updateSearch(self, event):
parameters = self.searchRepositoryEntry.get()
int = 0
currentList = self.searchResults.get(0, Tkinter.END)
length = len(parameters)
print(parameters)
print(length)
for i in currentList:
if not i[0:length] == parameters:
self.searchResults.delete(int)
print(i[0:length] == parameters)
print(i[0:length])
print(int)
int += 1


def getStudentList(self):
global fileDirectory # gets the directory that all the files are in
fileList = listdir(fileDirectory) # makes a list of files from the directory
self.studentList = [] # makes a new list
for file in fileList: # for loop that adds each item from the file list to the student list
self.studentList.append(file[:-4])

最佳答案

当您删除一个项目时,它下面的所有内容都会向上移动,从而导致所有后续项目的索引发生变化。此类问题的最简单解决方案(从文本小部件中删除单词时也很常见)是从末尾开始向后删除。

关于python - Tkinter 列表框没有正确删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5068871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com