global Num1
from Tkinter import *
Num1 = ""
def buttonNPush(n):
global Num1
Num1 = Num1+n
print Num1
def clearScr():
global Num1
Num1 = ""
root = Tk()
textbox = Entry(root)
textbox.pack(side=TOP)
#Create Frame with buttons numbered 0-9
frameButtons = Frame(root)
frameButtons.pack(side=LEFT)
button1 = Button(frameButtons, text="1", command=buttonNPush("1"))
button1.grid(row=0, column=0)
button2 = Button(frameButtons, text="2", command=buttonNPush("2"))
button2.grid(row=0, column=1)
button3 = Button(frameButtons, text="3", command=buttonNPush("3"))
button3.grid(row=0, column=2)
button4 = Button(frameButtons, text="4", command=buttonNPush("4"))
button4.grid(row=1, column=0)
button5 = Button(frameButtons, text="5", command=buttonNPush("5"))
button5.grid(row=1, column=1)
button6 = Button(frameButtons, text="6", command=buttonNPush("6"))
button6.grid(row=1, column=2)
button7 = Button(frameButtons, text="7", command=buttonNPush("7"))
button7.grid(row=2, column=0)
button8 = Button(frameButtons, text="8", command=buttonNPush("8"))
button8.grid(row=2, column=1)
button9 = Button(frameButtons, text="9", command=buttonNPush("9"))
button9.grid(row=2, column=2)
button0 = Button(frameButtons, text="0", command=buttonNPush("0"))
button0.grid(row=3, column=0)
buttonClear = Button(frameButtons, text="C", command=clearScr)
buttonClear.grid(row=4, column=0)
root.mainloop()
It just prints:
1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
How do I make it wait until I press the buttons to add the numbers to the string. The buttons also don't run the event that they are meant to run.
from Tkinter import *
def frame(root, side):
w = Frame(root)
w.pack(side=side, expand=YES, fill=BOTH)
return w
def button(root, side, text, command=None):
w = Button(root, text=text, command=command)
w.pack(side=side, expand=YES, fill=BOTH)
return w
class Calculator(Frame):
def __init__(self):
Frame.__init__(self)
self.option_add('*Font', 'Verdana 12 bold')
self.pack(expand=YES, fill=BOTH)
self.master.title('Simple Calculator')
self.master.iconname("calc1")
display = StringVar()
Entry(self, relief=SUNKEN, textvariable=display).pack(side=TOP, expand=YES, fill=BOTH)
for key in ("123", "456", "789", "-0."):
keyF = frame(self, TOP)
for char in key:
button(keyF, LEFT, char,
lambda w=display, c=char: w.set(w.get() + c))
opsF = frame(self, TOP)
for char in "+-*/=":
if char == '=':
btn = button(opsF, LEFT, char)
btn.bind('<ButtonRelease-1>',
lambda e, s=self, w=display: s.calc(w), '+')
else:
btn = button(opsF, LEFT, char,
lambda w=display, s=' %s '%char: w.set(w.get()+s))
clearF = frame(self, BOTTOM)
button(clearF, LEFT, 'Clr', lambda w=display: w.set(''))
def calc(self, display):
try:
display.set(eval(display.get()))
except:
display.set("ERROR")
if __name__ == '__main__':
Calculator().mainloop()