1、使用数据库编写关键代码,实现: (1) 登录对话框界面设计,包括用户名输入框、密码输入框、登录和取消按钮。(2)点击登录,判断输入是否正确,并做出提示。 (3)点击取消按钮,关闭登录对话框。
时间: 2024-03-02 07:50:46 浏览: 16
以下是使用Python和SQLite3实现的示例代码:
```python
import tkinter as tk
import sqlite3
class LoginDialog(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.title("Login")
self.parent = parent
self.result = None
# 创建用户名和密码输入框
tk.Label(self, text="Username:").grid(row=0, column=0, sticky="w")
self.username_entry = tk.Entry(self)
self.username_entry.grid(row=0, column=1)
tk.Label(self, text="Password:").grid(row=1, column=0, sticky="w")
self.password_entry = tk.Entry(self, show="*")
self.password_entry.grid(row=1, column=1)
# 创建登录和取消按钮
tk.Button(self, text="Login", command=self.login).grid(row=2, column=0, pady=10)
tk.Button(self, text="Cancel", command=self.cancel).grid(row=2, column=1, pady=10)
# 连接数据库
self.conn = sqlite3.connect("users.db")
self.cursor = self.conn.cursor()
def login(self):
# 获取输入的用户名和密码
username = self.username_entry.get()
password = self.password_entry.get()
# 查询数据库中是否存在该用户
self.cursor.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))
row = self.cursor.fetchone()
if row is None:
# 用户名或密码错误,弹出提示框
tk.messagebox.showerror("Error", "Invalid username or password!")
else:
# 登录成功,设置返回值并关闭对话框
self.result = row[0] # 返回用户ID
self.destroy()
def cancel(self):
# 取消登录,关闭对话框
self.destroy()
def __del__(self):
# 断开数据库连接
self.cursor.close()
self.conn.close()
# 测试代码
if __name__ == "__main__":
root = tk.Tk()
root.withdraw() # 隐藏主窗口
dialog = LoginDialog(root)
root.wait_window(dialog)
if dialog.result is not None:
print("Logged in as user", dialog.result)
else:
print("Login cancelled")
```
在上面的代码中,我们创建了一个名为LoginDialog的对话框类,其中包含了用户名、密码输入框和登录、取消按钮。当用户点击登录按钮时,我们将从输入框中获取用户名和密码,并在SQLite3数据库中查询是否存在该用户。如果存在则返回该用户的ID,否则弹出提示框。当用户点击取消按钮时,对话框将被关闭。
你可以根据自己的需求修改上述示例代码。请确保在使用数据库时使用适当的安全措施,如绑定参数,以避免SQL注入攻击。