为这个代码添加查询余额和更改密码的功能
时间: 2024-02-17 14:01:14 浏览: 15
好的,我可以帮您添加查询余额和更改密码的功能。以下是更新后的代码。
```python
import tkinter as tk
class ATM:
def __init__(self, master):
self.master = master
master.title("ATM Machine")
# 创建标签和文本框
self.balance_label = tk.Label(master, text="当前余额:")
self.balance_label.grid(row=0, column=0)
self.balance_entry = tk.Entry(master)
self.balance_entry.grid(row=0, column=1)
self.amount_label = tk.Label(master, text="金额:")
self.amount_label.grid(row=1, column=0)
self.amount_entry = tk.Entry(master)
self.amount_entry.grid(row=1, column=1)
self.password_label = tk.Label(master, text="密码:")
self.password_label.grid(row=2, column=0)
self.password_entry = tk.Entry(master, show="*")
self.password_entry.grid(row=2, column=1)
# 创建按钮
self.withdraw_button = tk.Button(master, text="取款", command=self.withdraw)
self.withdraw_button.grid(row=3, column=0)
self.deposit_button = tk.Button(master, text="存款", command=self.deposit)
self.deposit_button.grid(row=3, column=1)
self.balance_button = tk.Button(master, text="查询余额", command=self.check_balance)
self.balance_button.grid(row=4, column=0)
self.change_password_button = tk.Button(master, text="更改密码", command=self.change_password)
self.change_password_button.grid(row=4, column=1)
# 初始化余额和密码
self.balance = 1000
self.password = "1234"
def withdraw(self):
# 获取取款金额
amount = float(self.amount_entry.get())
# 检查余额是否充足
if amount > self.balance:
tk.messagebox.showerror("错误", "余额不足")
else:
# 更新余额
self.balance -= amount
self.balance_entry.delete(0, tk.END)
self.balance_entry.insert(0, self.balance)
def deposit(self):
# 获取存款金额
amount = float(self.amount_entry.get())
# 更新余额
self.balance += amount
self.balance_entry.delete(0, tk.END)
self.balance_entry.insert(0, self.balance)
def check_balance(self):
# 显示当前余额
tk.messagebox.showinfo("查询余额", f"当前余额为{self.balance}元")
def change_password(self):
# 获取用户输入的密码
new_password = self.password_entry.get()
# 检查密码是否正确
if new_password == self.password:
tk.messagebox.showerror("错误", "新密码不能与旧密码相同")
else:
# 更新密码
self.password = new_password
tk.messagebox.showinfo("更改密码", "密码已更改")
root = tk.Tk()
atm = ATM(root)
root.mainloop()
```
现在,用户可以使用“查询余额”按钮来查询他们的余额,使用“更改密码”按钮更改他们的密码。我们添加了一个新的密码文本框,并使用show="*"选项隐藏了输入的字符。在更改密码时,我们还检查新密码是否与旧密码相同,以确保安全性。