使用 Tkinter 计算器的按钮初始化绕过整数和浮点数

getting around ints and floats with button initialisation for Tkinter calculator

下面是这个问题的后续...

我已经完成了计算器,但问题是:

我的按钮都是使用 for 循环构建的;包括功能按钮。我喜欢这样的事实,即代码很短,并且真的不想去删除 for 循环中的所有功能按钮,但我可能不得不解决我没有得到除法返回的浮点值的问题的两个整数。

即根据这个计算器,12/8 = 1。

我有什么聪明的想法可以在不删除 for 循环中的运算符的情况下做到这一点吗?

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

from __future__ import division 作为程序的第一行。这将使 / 成为浮点除法运算符。当然,现在 8/4 将给出 2.0 而不是整数 2。(如果你还想要整数除法,你可以添加一个 // 按钮,但我想你希望它像标准的手持计算器一样工作。)