【问题标题】:Count how many times tkinter button is pressed计算按下 tkinter 按钮的次数
【发布时间】:2014-10-04 06:51:38
【问题描述】:

我正在为一个学校项目编写程序。这是一个在电影院预订门票的程序。我已经使用 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()            

如您所见,我使用计数器将值写入文本文件,但该值永远不会更新。任何帮助将不胜感激,并提前感谢您。

【问题讨论】:

  • 我认为 'command = self.colour()' 与 'command = lambda:self.color()' 具有相同的效果。

标签: python class button tkinter counter


【解决方案1】:

您是否正在查看文件“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()    

【讨论】:

  • 非常感谢。那真的很有用。我想我并没有真正跟踪我的程序在做什么。它实际上是我创建的最大程序的一部分(尽管实际程序还有很多)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多