03-06-2010, 09:00 AM
I am working on a Tkinter calculator, and I decided to add memory buttons. The M+ button adds to the memory, and M is supposed to fill the result box with the memory. I added a print statement after M+, so that once it is clicked, I confirm that the mem variable has value, yet it still gives me an error saying mem was referenced before assignment. Here is the part of the source giving me trouble:
And here is the full source.
And finally, here is the error message:
I have solved the problem, I simply added
at the top of the script and then in my click function I added:
And it seems to work, view the completed source, look here
Code:
elif key == 'M+':
mem = result.get()
print mem
result.delete(0, END)
elif key == 'M':
result.insert(END, mem)
Code:
from Tkinter import *
class calc(Frame):
def __init__(self):
global result
top = Tk()
top.title('UberCalc v2.0')
Frame.__init__(self)
result = Entry()
result.pack(side=TOP)
buttons = ['M+', 'M', '+/-', '1', '2', '3','4', '5', '6','7', '8', '9','.', '0', 'Clear']
operbtn = ['-','+', '*','/', '=']
ro = 1
col = 0
for x in buttons:
action = lambda y=x: onclick(y)
Button(self, text=x, width=5, relief='ridge', command=action).grid(row=ro, column=col)
col += 1
if col > 2:
col = 0
ro += 1
col = 4
ro = 1
for x in operbtn:
action = lambda y=x:onclick(y)
Button(self, text=x, width=5, relief='ridge', command=action).grid(row=ro, column=col)
ro += 1
def onclick(key):
global result
if key == '=':
try:
fetch = result.get()
answer = eval(fetch)
result.delete(0, END)
result.insert(0, answer)
except(ZeroDivisionError):
result.delete(0, END)
result.insert(0, 'Do not divide by zero please')
except(SyntaxError):
result.delete(0, END)
result.insert(0, '0')
elif key == 'Clear':
result.delete(0, END)
elif key == 'M+':
mem = result.get()
result.delete(0, END)
elif key == 'M':
result.insert(END, mem)
elif key == '+/-':
if result.get()[0] == '-':
result.delete(0)
else:
result.insert(0, '-')
else:
result.insert(END, key)
if __name__ == '__main__':
window = calc()
window.pack()
window.mainloop()
Python Wrote:Exception in Tkinter callbackIf anyone could lend some assistance I would be very grateful
Traceback (most recent call last):
File "F:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "F:\Documents and Settings\Administrator\Desktop\Coding\Python\My Projects\Under Development\GUI\Advanced_Calc.py", line 16, in <lambda>
action = lambda y=x: onclick(y)
File "F:\Documents and Settings\Administrator\Desktop\Coding\Python\My Projects\Under Development\GUI\Advanced_Calc.py", line 49, in onclick
result.insert(END, mem)
UnboundLocalError: local variable 'mem' referenced before assignment
I have solved the problem, I simply added
Code:
mem = ''
Code:
global mem