要求
编写程序计算在给定利率、指定年数的情况下投资的未来值。这个计算公式如下。
使用文本域输入投资额、年份和利率。当用户单击“calculate”按钮时,在文本域中显示未来的投资值,如图所示。
代码实现
import tkinter as tk
def calculate():
amount, years, rate = (float(entry.get()) for entry in entries)
future_value = amount * (1 + rate / 1200) ** (years * 12)
result.config(state="normal")
result.delete("1.0", tk.END)
result.insert(tk.END, f"{
future_value:.2f}")
result.config(state="disabled")
def add_row(window, text, row):
tk.Label(window, text=text).grid(row=row, sticky=tk.W)
entry = tk.Entry(window)
entry.grid(row=row, column=1)
return entry
window = tk.Tk()
window.title("第三次实验")
labels = ["Investment Amount:", "Years:", "Annual Interest Rate:"]
entries = [add_row(window, label, i) for i, label in enumerate(labels)]
result = tk.Text(window, height=1, width=20, state="disabled")
result.grid(row=len(labels), column=1, sticky=tk