daansteraan
daansteraan

Reputation: 103

getting around ints and floats with button initialisation for Tkinter calculator

Below is a follow on from this question...

Python & Tkinter - buttons command to set label textvariable issue

I've finished the calculator but here is the problem:

My buttons were all built using a for-loop; function buttons included. I like the fact that the code is short and don't really want to go and remove all function buttons from the for-loop but i might have to to get around the problem where I don't get a float value returned for the division of two integers.

i.e 12/8 = 1 according to this calculator.

Any clever ideas how I could do that without removing the operators form the for-loop?

from Tkinter import *
import Tkinter as tk
import tkMessageBox

# main window
root = Tk()
root.title('Calculator')

# button set
buttons = ['1','2','3','4','5','6','7','8','9','0','+','-','/','*','.']

sum_value = StringVar()

def appear(x):
    return lambda: output_window.insert(END,x)

# output window
output_window = tk.Entry(root, textvariable=sum_value, width=20, font = 'courier 10')
output_window.grid(row=0, columnspan=3, sticky=(E,W))

def equals():
    try:
        result = eval(output_window.get())
    except:
        result = 'INVALID'

    output_window.delete(0,END)
    output_window.insert(0,result)

def refresh():
    output_window.delete(0,END)

# button creation
r=1
c=0

for i in buttons:
    if c < 2:
        tk.Button(root, text = i, command = appear(i), pady = 3).grid(row = r, column = c, sticky = (N,S,E,W))        
        c += 1
    else:
        tk.Button(root, text = i, command = appear(i), pady = 3).grid(row = r,column = c,sticky = (N,S,E,W))
        r  += 1
        c = 0

# clear and equal button
equal = tk.Button(root,text='=',padx = 5, pady=3, command=equals)
equal.grid(row=6,column=0,sticky=(N,S,E,W))

clear = tk.Button(root,text='CLEAR',padx = 5, pady=3,command = refresh)
clear.grid(row=6,column=1, columnspan = 2,sticky=(N,S,E,W))


#menu
menubar = Menu(root)

def quit1():
    if tkMessageBox.askokcancel("Quit","Are you sure you want to quit?"):
        root.destroy()

viewMenu = Menu(menubar)
viewMenu.add_command(label='Quit', command = quit1)
menubar.add_cascade(label="Home", menu=viewMenu)


root.config(menu=menubar)
root.mainloop()

Upvotes: 0

Views: 258

Answers (1)

saulspatz
saulspatz

Reputation: 5261

Write from __future__ import division as the first line of your program. This will make / into the floating point division operator. Of course, now 8/4 will give 2.0 not the integer 2. (If you wanted integer division also, you could add a // button, but I gather you want this to work like a standard hand-held calculator.)

Upvotes: 2

Related Questions