Help passing variables.

A

aToaster

Hi guys, new to the forums. I'm starting to learn python and tkinter.
I started off by trying to make a simple calculator program and I
need to pass the calcTotal variable in and out of the ButtonHandler
function, how do I do this?

This is my program
# -----------------------------------------
from Tkinter import *

class CalcApp:
def __init__(self, parent):
self.myParent = parent
self.myContainer1 = Frame(parent)
self.myContainer1.pack()

# Button 1
button_name = "1"
self.button1 = Button(self.myContainer1,
command = lambda
arg1=1, arg2=button_name :
self.buttonHandler(arg1, arg2)
)

self.button1.configure(text=button_name)
self.button1.pack(side=LEFT)

# Button 2
button_name = "2"
self.button2 = Button(self.myContainer1,
command = lambda
arg1=2, arg2=button_name :
self.buttonHandler(arg1, arg2)
)
self.button2.configure(text=button_name)
self.button2.pack()


def buttonHandler(self, argument1, argument2):
print "You have clicked :", argument2
calcTotal = calcTotal + argument1
print calcTotal

def buttonHandler_a(self, argument1, argument2):
print "You have clicked :", argument2
calcTotal = calcTotal +argument1
print calcTotal

var calcTotal = 0
print "\n"*100
print "Starting program Calc."
root = Tk()
myapp = CalcApp(root)
print "Starting even loop."
root.mainloop()
print "Finished executing event loop."

#End of Program
# -----------------------------------------

Any help will be greatly appreciated! Thanks

,aToaster

PS. I love Python!
 
C

Christopher T King

I started off by trying to make a simple calculator program and I
need to pass the calcTotal variable in and out of the ButtonHandler
function, how do I do this?

The quick answer is that in buttonHandler_a(), you have to decalre
calcTotal global; otherwise it will assume it's a local value:

def buttonHandler_a(self, argument1, argument2):
global calcTotal
print "You have clicked :", argument2
calcTotal = calcTotal +argument1
print calcTotal

The long answer is that anytime you think you need a global variable, you
probably don't. The better way to go about this is to have calcTotal be a
property of CalcApp ("self.calcTotal = 0" in CalcApp.__init__()). This
way, CalcApp will be re-entrant, in the case that you ever need to
instantiate more than one of CalcApp (something you probably wouldn't do
with an application like that, but a good practice nonetheless).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top