按实体值对 tkinter 列表框中的项目进行排序

Order items in a listbox in tkinter by an entity value

我有一个排行榜,其中包含一些球探的信息。该信息的结构如下:ID,forname,surname,points。此信息存储在一个文件中,但在文件中没有按顺序排列。我不想改变这个。

我希望在更新列表框时(当我调用 calcPoints() 函数时),它会根据记录中的点实体从最大点到最小点对侦察员进行排序。下面是我的 calcPoints() 方法的代码。

谢谢

def _calcPoints():
        mainWin._leaderboard.delete(0,END)
        with open(tempFileName,'a') as ft:
            for sc in self._Scouts:
                sc._addPoints(-int(sc._getPoints()))
                with open(badgeFile,"r") as fb:
                    lines = fb.readlines()
                    for line in lines:
                        if sc._getID() == line.split(":")[0]:
                            badge = ((line.split(':')[1]).split(',')[0])
                            if badge == "Core":
                                sc._addPoints(5)
                            elif badge == 'Activity':
                                sc._addPoints(1)
                            elif badge == 'Challenge':
                                sc._addPoints(3)
                            elif badge == 'Activity Pack':
                                sc._addPoints(5)
                ft.write(sc.getInfo() + "\n")
        os.remove(leadFile)
        with open(leadFile,"a") as f:
            with open(tempFileName,"r") as ft:
                lines = ft.readlines()
                for line in lines:
                    f.write(line)
        os.remove(tempFileName)
        mainWin.addScoutsLeaderboard()
        return

直接调用sorted,按每行最后一个元素排序points,使用reverse=True会从高到低排序:

lines = sorted(fb,key=lambda x: float(x.rsplit(":",1)[1]),reverse=True)

不确定数据在哪个文件中,因此您的文件 object 和分隔符应与您的实际文件匹配,如果您有 header,则需要添加 header = next(fb)

如果您单独使用这些值,您可能会发现 csv 模块更适合:

import csv
with open(badgeFile,"r") as fb:
    r = csv.reader(fb,delimiter=":")
    lines = sorted(r, key=lambda x: float(x[1]), reverse=True)
    for fid,fname,sname,pnts in lines:

附带说明一下,您只需要在实际需要列表时调用 .readlines(),否则您可以遍历文件 object.