Python 计算按下tkinter按钮的次数

Python 计算按下tkinter按钮的次数,python,class,button,tkinter,counter,Python,Class,Button,Tkinter,Counter,我正在为一个学校项目写一个程序。这是一个在电影院订票的节目。我使用tkinter创建了一个gui,供用户选择他们想要的座位。但是,我还需要计算所选座位的数量,以打印门票的总成本。但我被困在这里,我不知道如何继续(我刚刚学习了一些课程,并没有完全理解它们)。到目前为止,用户可以选择和取消选择按钮。下面是使用的代码 class buttonc: def __init__(self,master,x,ro): self.x = x self.ro = ro

我正在为一个学校项目写一个程序。这是一个在电影院订票的节目。我使用tkinter创建了一个gui,供用户选择他们想要的座位。但是,我还需要计算所选座位的数量,以打印门票的总成本。但我被困在这里,我不知道如何继续(我刚刚学习了一些课程,并没有完全理解它们)。到目前为止,用户可以选择和取消选择按钮。下面是使用的代码

class buttonc:
    def __init__(self,master,x,ro):
        self.x = x
        self.ro = ro
        self.count = 0
        self.button = []
        self.button += [Button(root,text = self.x,background = "white",width= 2,height = 1,command = lambda:self.color())]
        self.click = 0

    def clicks(self,numm):
        self.click += numm
    def color(self):
        if self.count == 1:
            self.button[0].configure(background = "white")
            self.count = 0
            self.clicks(-1)
        elif self.count == 0:
            self.button[0].configure(background = "green")
            self.count = 1
            self.clicks(1)

    def counter(self):
        return self.click
    def pos(self):                
        self.button[0].grid(column = self.x+30,row = self.ro, padx = 14, pady = 14)
fo = open('tickets.txt','w')
for i in range(9):
    for k in range(25):
        b = buttonc(root,k+1,i+1)
        b.pos()
        fincount = str(b.counter())

root.mainloop()
fo.write(fincount)
fo.close()            

如您所见,我使用计数器将值写入文本文件,但该值从未更新。如果您有任何帮助,我们将不胜感激。

您是否正在查看文件“tickets.txt”并查看0?如果是这样的话,这并不奇怪。在进入主循环之前提取
b.counter()

重新排列代码,如下所示:

buttons = []

for i in range(9):
    for k in range(25):
        b = buttonc(root,k+1,i+1)
        b.pos()
        buttons.append(b)

root.mainloop()
fo = open('tickets.txt','w')
for b in buttons:
    fo.write(str(b.counter() + "\n")
fo.close()    

我认为“command=self.color()”与“command=lambda:self.color()”具有相同的效果。非常感谢。那真的很有用。我想我没有真正了解我的程序在做什么。这实际上是我创建的最大程序的一部分(尽管实际程序还有很多)。