1.新建文件,运行界面要求如下: (1)假定用户名为“admin”,密码为“123456”,如果用户名和密码正确,显示如下界面。 (2)如果用户名或密码不正确,显示如下界面。 (3)单击“重填”按钮,清空两个输入框。
时间: 2023-12-06 18:03:22 浏览: 31
好的,以下是 Python 代码实现:
```python
import tkinter as tk
def check_login():
username = entry_username.get().strip()
password = entry_password.get().strip()
if username == "admin" and password == "123456":
label_result.config(text="登录成功!", fg="green")
else:
label_result.config(text="用户名或密码不正确!", fg="red")
entry_username.delete(0, tk.END)
entry_password.delete(0, tk.END)
window = tk.Tk()
window.title("登录界面")
window.geometry("300x200")
label_username = tk.Label(window, text="用户名:")
label_username.pack()
entry_username = tk.Entry(window)
entry_username.pack()
label_password = tk.Label(window, text="密码:")
label_password.pack()
entry_password = tk.Entry(window, show="*")
entry_password.pack()
button_login = tk.Button(window, text="登录", command=check_login)
button_login.pack()
button_clear = tk.Button(window, text="重填", command=lambda: (entry_username.delete(0, tk.END), entry_password.delete(0, tk.END)))
button_clear.pack()
label_result = tk.Label(window, text="")
label_result.pack()
window.mainloop()
```
我们使用 `tkinter` 模块创建了一个 GUI 窗口,包括用户名和密码的输入框、登录按钮、重填按钮和结果提示标签。当用户单击登录按钮时,我们会读取用户名和密码输入框中的内容,并检查是否与预设的用户名和密码匹配。如果匹配成功,则将结果提示标签的文本改为“登录成功!”并将字体颜色设为绿色。如果匹配失败,则将结果提示标签的文本改为“用户名或密码不正确!”并将字体颜色设为红色。同时,我们会清空用户名和密码输入框中的内容。
注意,在调用 `button_clear` 的回调函数时,我们使用了 `lambda` 表达式,以便同时清空两个输入框。