简体   繁体   中英

Count how many times tkinter button is pressed

I am writing a program for a school project. It is a program to book tickets at a cinema theater. I have used tkinter to create a gui for users to select their desired seats. However, I also need to count the number of seats selected, to print the total cost of tickets. But I am stuck here and I am not sure how to proceed(I have just learned classes and do not fully understand them). So far users can select and deselect the buttons. Here is the code that is used.

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()            

As you can see i have used a counter to write the value into a text file, but this value never gets updated. Any help would be appreciated, and thank you in advance.

Are you looking into the file "tickets.txt" and see a 0? If so, it's not really surprising. You extract b.counter() before you enter the main loop.

Rearrange your code like:

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()    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM