1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| import pymysql import customtkinter
def connect_db(): """连接数据库函数
Args: None
Returns: pymysql.connections.Connection: 数据库连接对象,若连接失败则返回None """
try: conn = pymysql.connect( host = 'mysql.sqlpub.com', user = 'yuxuan1012', passwd = 'Ki1jpS4leURR4TFu', port = 3306, db = 'yuxuan1012', charset = 'utf8' ) return conn except pymysql.err.OperationalError as e: print(f"数据库连接失败:{e}") customtkinter.messagebox.showerror("错误", "连接数据库失败,请检查网络和数据库配置。") return None
def register(): """用户注册函数
Args: None """
username = entry_username.get() password = entry_password.get() confirm_password = entry_confirm_password.get()
if password != confirm_password: customtkinter.messagebox.showwarning("警告", "两次输入的密码不一致!") return
conn = connect_db()
if conn: try: with conn.cursor() as cursor: cursor.execute("SHOW TABLES LIKE 'users'") exists = cursor.fetchone() if not exists: cursor.execute("CREATE TABLE users (username VARCHAR(50), password VARCHAR(50))")
sql = "INSERT INTO users (username, password) VALUES (%s, %s)" cursor.execute(sql, (username, password)) conn.commit() print("注册成功!") except pymysql.err.Error as e: print(f"数据库操作错误:{e}") customtkinter.messagebox.showerror("错误", "注册失败,请检查数据库配置或联系管理员。") finally: conn.close() else: customtkinter.messagebox.showerror("错误", "注册失败,请检查网络连接或管理员。")
customtkinter.set_appearance_mode("Dark") customtkinter.set_default_color_theme("green")
root = customtkinter.CTk() root.geometry("400x300")
frame = customtkinter.CTkFrame(master=root) frame.pack(pady=20, padx=60, fill="both", expand=True)
label = customtkinter.CTkLabel(master=frame, text="注册", font=("Roboto", 24)) label.pack(pady=12, padx=10)
entry_username = customtkinter.CTkEntry(master=frame, placeholder_text="注册用户名") entry_username.pack(pady=12, padx=10) entry_password = customtkinter.CTkEntry(master=frame, placeholder_text="注册密码", show="*") entry_password.pack(pady=12, padx=10) entry_confirm_password = customtkinter.CTkEntry(master=frame, placeholder_text="确认密码", show="*") entry_confirm_password.pack(pady=12, padx=10)
button = customtkinter.CTkButton(master=frame, text="注册", command=register) button.pack(pady=12, padx=10)
root.mainloop()
|