打开和关闭复选框?

时间:2014-06-23 15:49:38

标签: python checkbox tkinter

我需要帮助,了解如何使用复选框我已经在选中时关闭了程序的一部分,并在复选框关闭时关闭另一部分。我的想法是,当复选框打开时,我希望打开addPercTip(self)部分并关闭addRateTip,反之亦然,当复选框关闭时。 PercTip off和RateTip on。我现在的问题是,在我的计算中,它试图从两个部分获取信息,因此其中一个需要关闭。任何帮助都会非常感激!

from Tkinter import *

class App(Tk):
    def __init__(self):
        Tk.__init__(self)

        self.headerFont = ("Times", "16", "italic")
        self.title("Restaurant Tipper")
        self.addOrigBill()
        self.addChooseOne()
        self.addPercTip()
        self.addRateTip()
        self.addOutput()


    def addChooseOne(self):
        Label(self, text = "Check ON for % check OFF for rating!",
            font = self.headerFont).grid(row = 2, column = 1)
        self.checkVar = IntVar()
        self.chkCheck = Checkbutton(self, variable = self.checkVar)
        self.chkCheck.grid(row = 3, column = 1)


    def calculate(self):
        bill = float(self.txtBillAmount.get())
        percTip = self.percVar
        rateTip = int(self.scrScale.get())

        tip = bill * percTip
        self.lblTip["text"] = "%.2f" % tip

        totalBill = tip + bill
        self.lblTotalBill["text"] = "%.2f" % totalBill

        if rateTip <= 2:
            percTip = .10

        elif 3 <= rateTip <= 4:
            percTip = .12

        elif 5 <= rateTip <= 6:
            percTip = .15

        elif 7 <= rateTip <= 8:
            percTip = .17

        elif 9 <= rateTip <= 10:
            percTip = .20

        else:
            self.lblTotalBill["text"] = "Something is wrong"

def main():
    app = App()
    app.mainloop()

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

实例化一个checkbutton时,可以设置一个命令属性。这是一个只要选中按钮就会调用的函数。

self.chkCheck(self, variable = self.checkVar, command = doStuff)

def doStuff(self)
    print 'doing stuff'

编辑:

关于以下评论:

def doStuff(self):
    if self.checkVar.get() == 1:  <<<1 is the 'checked value'
        percTip = True
        rateTip = False

但是,您实际上并不需要这样做。在您的calculate()函数中,您可以简单地调用self.checkVar.get(),如果它是1则进行评估,如果为0(未选中),则进行不同的评估等。

相关问题