Python迭代按钮计数器

时间:2018-03-27 09:47:28

标签: python variables for-loop

我当前的代码用于构建健身房例程。我目前正在构建一个删除练习的功能。为此,我在每个练习的侧面创建了一个小部件,单击该小部件时应删除该练习。我使用for循环创建了这些小部件,并创建了一个名为Counter的变量,该变量被分配了练习的数量。然后将此小部件链接到应删除练习的功能。我的问题是,我点击计数器的任何按钮都是相同的,这是最大值。这是当前的代码:

    Count = -1
    Count4 = 0
    for item in Sets_ID:
        Count = Count + 1
        if RoutinesCount == 0:            
            self.Delete = Button(self.FrameRoutine, bg = "PaleTurquoise1", font =("Arial","16"), text = "X", command = self.DeleteExercise)
            self.Delete.grid(row = 5+Count, column = 5)
        else:
            Count4 = Count4 + 2
            self.Delete2 = Button(self.FrameRoutine, bg = "PaleTurquoise1", font =("Arial","16"), text = "X", command = self.DeleteExercise)
            self.Delete2.grid(row = 8 + Count + Count4, column = 5)


def DeleteExercise(self):
    global Count  

    print (Count)

我的问题是计数器总是具有最大值,因为它在小部件的for循环中递增。我不知道如何分配计数器小部件的数量。

1 个答案:

答案 0 :(得分:0)

我认为你有变量和范围问题。只需在外部变量范围内声明计数器,然后在DeleteExercise函数中重置它。如果您使用类,请将其另存为属性。

class MYBigWidget():
    def __init__(self):
        self.Count = -1
        self.Count4 = 0

    def Buildier():
        for item in Sets_ID:
            self.Count = self.Count + 1
            if RoutinesCount == 0:            
                self.Delete = Button(self.FrameRoutine, bg = "PaleTurquoise1", font =("Arial","16"), text = "X", command = self.DeleteExercise)
                self.Delete.grid(row = 5+Count, column = 5)
            else:
                self.Count4 = self.Count4 + 2
                self.Delete2 = Button(self.FrameRoutine, bg =    "PaleTurquoise1", font =("Arial","16"), text = "X", command =    self.DeleteExercise)
                self.Delete2.grid(row = 8 + self.Count + self.Count4, column = 5)


    def DeleteExercise(self):
        print self.Count