问题描述:

I need help understanding how I can use the checkbox I've made turn a part of the program off when checked on and turn another part off when the checkbox is off. My idea is that when the checkbox is on, I want the addPercTip(self) section to be turned on and the addRateTip to be turned off, and vice-versa when the checkbox is off. PercTip off and RateTip on. My problem right now is that in my calculations, it is trying to take info from both parts, so one of them needs to be off. Any help would be enormously appreciated!

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

网友答案:

When you instantiate a checkbutton you can set a command attribute. This is a function that will be called whenever the button is checked.

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

def doStuff(self)
    print 'doing stuff'

EDIT:

As to the comment below:

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

However, you don't actually need to do that. In your calculate() function you could simply call self.checkVar.get() and if it is 1 then evaluate and if 0 (unchecked) then evaluate differently etc.

相关阅读:
Top