以下是此问题的后续内容......
Python & Tkinter - buttons command to set label textvariable issue
我已经完成了计算器,但问题出在这里:
我的按钮都是使用for循环构建的;包括功能按钮。我喜欢这样的事实,即代码很短,并不想真正去除for-loop中的所有功能按钮,但我可能不得不解决问题,我没有得到为该部门返回的浮点值两个整数。
根据这个计算器,即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()