import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import sqlite3
from ttkthemes import ThemedStyle
class StudentCourseApp:
def __init__(self, master, db_conn):
self.master = master
self.master.title("学生选课系统")
self.db_conn = db_conn
style = ThemedStyle(self.master)
style.set_theme("equilux")
self.label_name = ttk.Label(master, text="姓名:")
self.label_name.pack(pady=5)
self.entry_name = ttk.Entry(master)
self.entry_name.pack(pady=5)
self.label_course = ttk.Label(master, text="课程:")
self.label_course.pack(pady=5)
self.entry_course = ttk.Entry(master)
self.entry_course.pack(pady=5)
self.add_course_button = ttk.Button(master, text="选择课程", command=self.add_course)
self.add_course_button.pack(pady=10)
self.label_list = ttk.Label(master, text="已选课程列表:")
self.label_list.pack(pady=5)
self.listbox = tk.Listbox(master, height=10, width=40)
self.listbox.pack()
self.login_button = ttk.Button(master, text="学生登录", command=self.open_student_account_page)
self.login_button.pack(pady=10)
self.admin_button = ttk.Button(master, text="管理员登录", command=self.open_admin_page)
self.admin_button.pack(pady=10)
def add_course(self):
student_name = self.entry_name.get().strip()
student_course = self.entry_course.get().strip()
if student_name and student_course:
course_message = f"{student_name} - 课程: {student_course}"
self.listbox.insert(tk.END, course_message)
self.entry_name.delete(0, tk.END)
self.entry_course.delete(0, tk.END)
self.save_course_to_db(student_name, student_course)
else:
messagebox.showwarning("错误", "请输入学生姓名和课程!")
def save_course_to_db(self, student_name, student_course):
try:
cursor = self.db_conn.cursor()
cursor.execute("INSERT INTO student_courses (student_name, course_name) VALUES (?, ?)", (student_name, student_course))
self.db_conn.commit()
except Exception as e:
messagebox.showerror("数据库错误", str(e))
def open_student_account_page(self):
student_account_window = tk.Toplevel(self.master)
student_account_window.title("学生账户页面")
student_account_page = StudentAccountApp(student_account_window, self.db_conn, self)
def open_admin_page(self):
password = simpledialog.askstring("管理员登录", "请输入管理员密码:", show='*')
if password == "123":
admin_window = tk.Toplevel(self.master)
admin_window.title("管理员页面")
admin_page = AdminPage(admin_window, self.db_conn, self.listbox, self)
else:
messagebox.showwarning("错误", "密码错误!")
class StudentAccountApp:
def __init__(self, master, db_conn, main_app):
self.master = master
self.db_conn = db_conn
self.main_app = main_app
style = ThemedStyle(self.master)
style.set_theme("equilux")
self.label_username = ttk.Label(master, text="用户名:")
self.label_username.pack(pady=5)
self.entry_username = ttk.Entry(master)
self.entry_username.pack(pady=5)
self.label_password = ttk.Label(master, text="密码:")
self.label_password.pack(pady=5)
self.entry_password = ttk.Entry(master, show="*")
self.entry_password.pack(pady=5)
self.login_button = ttk.Button(master, text="登录", command=self.login)
self.login_button.pack(pady=10)
self.register_button = ttk.Button(master, text="注册", command=self.register)
self.register_button.pack(pady=10)
self.label_courses = ttk.Label(master, text="已选课程:")
self.label_courses.pack(pady=5)
self.listbox_courses = tk.Listbox(master, height=10, width=40)
self.listbox_courses.pack()
def login(self):
username = self.entry_username.get().strip()
password = self.entry_password.get().strip()
if username and password:
if self.validate_student_login(username, password):
self.load_student_courses(username)
else:
messagebox.showwarning("错误", "用户名或密码错误!")
else:
messagebox.showwarning("错误", "请输入用户名和密码!")
def register(self):
username = self.entry_username.get().strip()
password = self.entry_password.get().strip()
if username and password:
if not self.validate_username_exist(username):
self.save_student_to_db(username, password)
self.load_student_courses(username)
else:
messagebox.showwarning("错误", "用户名已存在,请选择其他用户名!")
else:
messagebox.showwarning("错误", "请输入用户名和密码!")
def validate_student_login(self, username, password):
try:
cursor = self.db_conn.cursor()
cursor.execute("SELECT * FROM students WHERE username=? AND password=?", (username, password))
return cursor.fetchone() is not None
except Exception as e:
messagebox.showerror("数据库错误", str(e))
return False
def validate_username_exist(self, username):
try:
cursor = self.db_conn.cursor()
cursor.execute("SELECT * FROM students WHERE username=?", (username,))
return cursor.fetchone() is not None
except Exception as e:
messagebox.showerror("数据库错误", str(e))
return True
def save_student_to_db(self, username, password):
try:
cursor = self.db_conn.cursor()
cursor.execute("INSERT INTO students (username, password) VALUES (?, ?)", (username, password))
self.db_conn.commit()
messagebox.showinfo("注册成功", "学生账户创建成功!")
except Exception as e:
messagebox.showerror("数据库错误", str(e))
def load_student_courses(self, username):
try:
cursor = self.db_conn.cursor()
cursor.execute("SELECT * FROM student_courses WHERE student_name=?", (username,))
courses = cursor.fetchall()
self.listbox_courses.delete(0, tk.END)
for course in courses:
course_message = f"{course[1]} - 课程: {course[2]}"
self.listbox_courses.insert(tk.END, course_message)
except Exception as e:
messagebox.showerror("数据库错误", str(e))
class AdminPage:
def __init__(self, master, db_conn, listbox, app):
self.master = master
self.db_conn = db_conn
self.listbox = listbox
self.app = app
# 创建主题样式
style = ThemedStyle(self.master)
style.set_theme("equilux") # 使用Equilux主题,您可以根据需要选择其他主题
self.view_courses_button = ttk.Button(master, text="查看学生选课", command=self.view_courses)
self.view_courses_button.pack(pady=10)
self.add_course_button = ttk.Button(master, text="添加课程", command=self.add_course)
self.add_course_button.pack(pady=10)
self.delete_course_button = ttk.Button(master, text="删除课程", command=self.delete_course)
self.delete_course_button.pack(pady=10)
self.quit_button = ttk.Button(master, text="退出", command=master.destroy)
self.quit_button.pack(pady=10)
def update_user_interface(self, course_message):
self.listbox.insert(tk.END, course_message)
def update_course_list(self):
self.listbox.delete(0, tk.END)
cursor = self.db_conn.cursor()
cursor.execute("SELECT * FROM student_courses")
courses = cursor.fetchall()
for course in courses:
course_message = f"{course[1]} - 课程: {course[2]}"
self.listbox.insert(tk.END, course_message)
def view_courses(self):
cursor = self.db_conn.cursor()
cursor.execute("SELECT * FROM student_courses")
courses = cursor.fetchall()
if courses:
course_list = "\n".join([f"{course[1]} - 课程: {course[2]}" for course in courses])
messagebox.showinfo("学生选课列表", course_list)
else:
messagebox.showwarning("提示", "还没有学生选课!")
def add_course(self):
student_name = simpledialog.askstring("添加课程", "请输入学生姓名:")
if student_name:
student_course = simpledialog.askstring("添加课程", "请输入学生课程:")
if student_course:
self.save_course_to_db(student_name, student_course)
messagebox.showinfo("提示", "课程添加成功!")
# 同步更新到用户界面
self.app.update_user_interface(f"{student_name} - 课程: {student_course}")
else:
messagebox.showwarning("错误", "请输入有效的学生课程!")
else:
messagebox.showwarning("错误", "请输入有效的学生姓名!")
def save_course_to_db(self, student_name, student_course):
try:
cursor = self.db_conn.cursor()
cursor.execute("INSERT INTO student_courses (student_name, course_name) VALUES (?, ?)", (student_name, student_course))
self.db_conn.commit()
except Exception as e:
messagebox.showerror("数据库错误", str(e))
def delete_course(self):
selected_indices = self.listbox.curselection()
if selected_indices:
if messagebox.askyesno("删除课程", "确定要删除选中的课程吗?"):
for i in selected_indices:
course_message = self.listbox.get(i)
student_name = course_message.split("-")[0].strip()
try:
cursor = self.db_conn.cursor()
cursor.execute("DELETE FROM student_courses WHERE student_name=?", (student_name,))
self.db_conn.commit()
self.listbox.delete(i)
# 同步更新到用户界面
if self.app:
self.app.update_user_interface(f"{student_name} 的选课信息已删除。")
except Exception as e:
messagebox.showerror("数据库错误", str(e))
else:
messagebox.showwarning("错误", "请选择要删除的课程!")
def create_tables_if_not_exist(cursor):
cursor.execute("CREATE TABLE IF NOT EXISTS student_courses (id INTEGER PRIMARY KEY AUTOINCREMENT, student_name TEXT, course_name TEXT)")
cursor.execute("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
def main():
db_conn = sqlite3.connect("grades.db")
cursor = db_conn.cursor()
create_tables_if_not_exist(cursor)
root = tk.Tk()
app = StudentCourseApp(root, db_conn)
root.mainloop()
db_conn.close()
if __name__ == "__main__":
main()
import tkinter as tk
from tkinter import messagebox, simpledialog
import sqlite3
class StudentGradeApp:
def __init__(self, master, db_conn):
self.master = master
self.master.title("学生选课管理系统")
self.db_conn = db_conn
self.label_name = tk.Label(master, text="姓名:")
self.label_name.pack()
self.entry_name = tk.Entry(master)
self.entry_name.pack()
self.label_score = tk.Label(master, text="课程:")
self.label_score.pack()
self.entry_score = tk.Entry(master)
self.entry_score.pack()
self.add_grade_button = tk.Button(master, text="添加课程", bg="#4caf50", fg="white", command=self.add_grade)
self.add_grade_button.pack(pady=10)
self.label_list = tk.Label(master, text="课程列表:")
self.label_list.pack()
self.listbox = tk.Listbox(master, height=10, width=40)
self.listbox.pack()
self.admin_button = tk.Button(master, text="管理员登录", bg="#2196f3", fg="white", command=self.open_admin_page)
self.admin_button.pack(pady=10)
def add_grade(self):
student_name = self.entry_name.get().strip()
student_score = self.entry_score.get().strip()
if student_name and student_score:
grade_message = f"{student_name} - 课程: {student_score}"
self.listbox.insert(tk.END, grade_message)
self.entry_name.delete(0, tk.END)
self.entry_score.delete(0, tk.END)
# 将课程信息保存到数据库
self.save_grade_to_db(student_name, student_score)
# 同步更新到管理员页面
if self.admin_page:
self.admin_page.update_grade_list()
else:
messagebox.showwarning("错误", "请输入学生姓名和课程!")
def save_grade_to_db(self, student_name, student_score):
try:
cursor = self.db_conn.cursor()
cursor.execute("INSERT INTO student_grades (student_name, student_score) VALUES (?, ?)", (student_name, student_score))
self.db_conn.commit()
except Exception as e:
messagebox.showerror("数据库错误", str(e))
def open_admin_page(self):
password = simpledialog.askstring("管理员登录", "请输入管理员密码:", show='*')
if password == "123": # 简单的密码验证,实际使用中应该采用更安全的方式
admin_window = tk.Toplevel(self.master)
admin_window.title("管理员页面")
self.admin_page = AdminPage(admin_window, self.db_conn, self.listbox, self)
else:
messagebox.showwarning("错误", "密码错误!")
class AdminPage:
def __init__(self, master, db_conn, listbox, app):
self.master = master
self.db_conn = db_conn
self.listbox = listbox
self.app = app
self.view_grades_button = tk.Button(master, text="查看课程", bg="#4caf50", fg="white", command=self.view_grades)
self.view_grades_button.pack(pady=10)
self.add_grade_button = tk.Button(master, text="添加课程", bg="#2196f3", fg="white", command=self.add_grade)
self.add_grade_button.pack(pady=10)
self.delete_grade_button = tk.Button(master, text="删除课程", bg="#f44336", fg="white", command=self.delete_grade)
self.delete_grade_button.pack(pady=10)
self.update_grade_button = tk.Button(master, text="修改课程", bg="#ff9800", fg="white", command=self.update_grade)
self.update_grade_button.pack(pady=10)
self.quit_button = tk.Button(master, text="退出", bg="#607d8b", fg="white", command=master.destroy)
self.quit_button.pack(pady=10)
def update_user_interface(self, grade_message):
self.listbox.insert(tk.END, grade_message)
def update_grade_list(self):
self.listbox.delete(0, tk.END)
cursor = self.db_conn.cursor()
cursor.execute("SELECT * FROM student_grades")
grades = cursor.fetchall()
for grade in grades:
grade_message = f"{grade[1]} - 课程: {grade[2]}"
self.listbox.insert(tk.END, grade_message)
def view_grades(self):
cursor = self.db_conn.cursor()
cursor.execute("SELECT * FROM student_grades")
grades = cursor.fetchall()
if grades:
grade_list = "\n".join([f"{grade[1]} - 课程: {grade[2]}" for grade in grades])
messagebox.showinfo("学生课程列表", grade_list)
else:
messagebox.showwarning("提示", "还没有学生课程!")
def add_grade(self):
student_name = simpledialog.askstring("添加课程", "请输入学生姓名:")
if student_name:
student_score = simpledialog.askinteger("添加课程", "请输入学生课程:")
if student_score is not None:
self.save_grade_to_db(student_name, student_score)
messagebox.showinfo("提示", "课程添加成功!")
# 同步更新到用户界面
self.app.update_user_interface(f"{student_name} - 课程: {student_score}")
else:
messagebox.showwarning("错误", "请输入有效的学生课程!")
else:
messagebox.showwarning("错误", "请输入有效的学生姓名!")
def save_grade_to_db(self, student_name, student_score):
try:
cursor = self.db_conn.cursor()
cursor.execute("INSERT INTO student_grades (student_name, student_score) VALUES (?, ?)", (student_name, student_score))
self.db_conn.commit()
except Exception as e:
messagebox.showerror("数据库错误", str(e))
def delete_grade(self):
selected_indices = self.listbox.curselection()
if selected_indices:
if messagebox.askyesno("删除课程", "确定要删除选中的课程吗?"):
for i in selected_indices:
grade_message = self.listbox.get(i)
student_name = grade_message.split("-")[0].strip()
try:
cursor = self.db_conn.cursor()
cursor.execute("DELETE FROM student_grades WHERE student_name=?", (student_name,))
self.db_conn.commit()
self.listbox.delete(i)
# 同步更新到用户界面
if self.app:
self.app.update_user_interface(f"{student_name} 的成绩已删除。")
except Exception as e:
messagebox.showerror("数据库错误", str(e))
else:
messagebox.showwarning("错误", "请选择要删除的课程!")
def update_grade(self):
selected_indices = self.listbox.curselection()
if selected_indices:
if len(selected_indices) > 1:
messagebox.showwarning("错误", "一次只能修改一个学生的课程!")
else:
old_grade_message = self.listbox.get(selected_indices[0])
old_student_name, old_student_score = self.parse_grade_message(old_grade_message)
new_student_name = simpledialog.askstring("修改姓名", "请输入学生姓名:", initialvalue=old_student_name)
if new_student_name:
new_student_score = simpledialog.askinteger("修改课程", "请输入新的学生课程:", initialvalue=old_student_score)
if new_student_score is not None:
try:
cursor = self.db_conn.cursor()
cursor.execute("UPDATE student_grades SET student_name=?, student_score=? WHERE student_name=?", (new_student_name, new_student_score, old_student_name))
self.db_conn.commit()
new_grade_message = f"{new_student_name} - 课程: {new_student_score}"
self.listbox.delete(selected_indices[0])
self.listbox.insert(selected_indices[0], new_grade_message)
# 同步更新到用户界面
if self.app:
self.app.update_user_interface(f"{old_student_name} 的课程已修改为 {new_student_name} - 课程: {new_student_score}")
except Exception as e:
messagebox.showerror("数据库错误", str(e))
else:
messagebox.showwarning("错误", "请输入有效的学生课程!")
else:
messagebox.showwarning("错误", "请输入有效的学生姓名!")
else:
messagebox.showwarning("错误", "请选择要修改的课程!")
def parse_grade_message(self, grade_message):
student_name, _, student_score = grade_message.partition("-")
student_name = student_name.strip()
student_score = int(student_score.strip().split()[-1])
return student_name, student_score
def create_table_if_not_exists(cursor):
cursor.execute("CREATE TABLE IF NOT EXISTS student_grades (id INTEGER PRIMARY KEY AUTOINCREMENT, student_name TEXT, student_score INTEGER)")
def main():
# 连接到数据库
db_conn = sqlite3.connect("grades.db")
cursor = db_conn.cursor()
# 创建数据表
create_table_if_not_exists(cursor)
# 启动应用程序
root = tk.Tk()
app = StudentGradeApp(root, db_conn)
root.mainloop()
# 关闭数据库连接
db_conn.close()
if __name__ == "__main__":
main()
数据库mysql
import sqlite3
def view_data(db_file):
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# 查询 student_courses 表的数据
cursor.execute("SELECT * FROM student_courses")
courses = cursor.fetchall()
print("Student Courses:")
for course in courses:
print(course)
# 查询 students 表的数据
cursor.execute("SELECT * FROM students")
students = cursor.fetchall()
print("\nStudents:")
for student in students:
print(student)
except sqlite3.Error as e:
print("SQLite error:", e)
finally:
if conn:
conn.close()
# 调用函数并传入数据库文件路径
db_file_path = "grades.db"
view_data(db_file_path)