db_config.py里有# 1. MySQL数据库连接信息
HOST='localhost'
USER='root'
PWD='root'
DB_PORT=3306
DB_NAME='test'
def get_header(tab_name='course'):
'''
根据表名称返回表的标题
:param tab_name: 表的名称
:return: list, 表的标题行
'''
header=None
if tab_name=='course':
header=['Cno', 'Cname', 'Cpno', 'Ccredit']
elif tab_name=='student':
header=['Sno', 'Sname', 'Ssex', 'Sage', 'Sdept']
elif tab_name=='sc':
header=['Sno', 'Cno', 'Grade']
elif tab_name=='homework':
header=['Sno','Sname','Cno','Hyime','Grade']
elif tab_name=='ducsum':
header=['Sno','Sname','Algrade','Avagrade','Rankwork']
return header
def trans_data(dict_results):
'''
将[ {'Cno': '01', 'Cname': '高等数学', 'Cpno': None, 'Ccredit': 4}, {'Cno': '02', 'Cname': '大学物理', 'Cpno': '01', 'Ccredit': 3} ]
转换为:[('01', '高等数学', None, 4), ('02', '大学物理', '01', 3) ]
:param dict_results:
:return:
'''
ll=[]
for dict in dict_results:
ll.append(list(dict.values()))
return ll fetch_data_mysql.py里有import pymysql.cursors
import db_config
def getData(tab_name='tbcourse'):
# Connect to the database
connection = pymysql.connect(host=db_config.HOST,
user=db_config.USER,
port=db_config.DB_PORT,
password=db_config.PWD,
database=db_config.DB_NAME,
cursorclass=pymysql.cursors.Cursor)
# 使用pymysql.cursors.Cursor时,结果类似于: ( ('01', '高等数学', None, 4), ('02', '大学物理', '01', 3) )
# 使用pymysql.cursors.DictCursor时,结果类似于:[ {'Cno': '01', 'Cname': '高等数学', 'Cpno': None, 'Ccredit': 4}, {'Cno': '02', 'Cname': '大学物理', 'Cpno': '01', 'Ccredit': 3} ]
with connection:
with connection.cursor() as cursor:
# Read a single record
sql = f"SELECT * FROM {tab_name};"
# cursor.execute(sql, ('webmaster@python.org',))
cursor.execute(sql)
results = cursor.fetchall()
return results
def getData_aim(Sno,tab_name='tbcourse'):
# Connect to the database
connection = pymysql.connect(host=db_config.HOST,
user=db_config.USER,
port=db_config.DB_PORT,
password=db_config.PWD,
database=db_config.DB_NAME,
cursorclass=pymysql.cursors.Cursor)
# 使用pymysql.cursors.Cursor时,结果类似于: ( ('01', '高等数学', None, 4), ('02', '大学物理', '01', 3) )
# 使用pymysql.cursors.DictCursor时,结果类似于:[ {'Cno': '01', 'Cname': '高等数学', 'Cpno': None, 'Ccredit': 4}, {'Cno': '02', 'Cname': '大学物理', 'Cpno': '01', 'Ccredit': 3} ]
with connection:
with connection.cursor() as cursor:
# Read a single record
sql = f"SELECT * FROM {tab_name} where SNO=%s;"
cursor.execute(sql, ('Sno',))
# cursor.execute(sql,(department,))
results = cursor.fetchall()
return results
def del_row(cno, tab_name='tbCourse'):
# Connect to the database
connection = pymysql.connect(host=db_config.HOST,
user=db_config.USER,
port=db_config.DB_PORT,
password=db_config.PWD,
database=db_config.DB_NAME,
cursorclass=pymysql.cursors.Cursor)
with connection:
try:
with connection.cursor() as cursor:
# 表格名称不能使用占位符,只能拼接字符串
sql = f"DELETE FROM {tab_name} where CNO=%s;"
affected_rows=cursor.execute(sql, (cno,))
# connection is not autocommit by default. So you must commit to save your changes.
connection.commit()
except:
return 0
return affected_rows
def insert_row(values, tab_name='tbCourse'):
# 这里我们只处理输入值数目为4个的情况
if ((not isinstance(values, list)) and (not isinstance(values,tuple))) or len(values)!=4:
raise Exception('type error or length incorrect!!!')
# Connect to the database
connection = pymysql.connect(host=db_config.HOST,
user=db_config.USER,
port=db_config.DB_PORT,
password=db_config.PWD,
database=db_config.DB_NAME,
cursorclass=pymysql.cursors.Cursor)
with connection:
try:
with connection.cursor() as cursor:
# 表格名称不能使用占位符,只能拼接字符串
sql = f"insert into {tab_name} values (%s, %s, %s, %s);"
affected_rows = cursor.execute(sql, values)
# connection is not autocommit by default. So you must commit to save your changes.
connection.commit()
except:
return 0
return affected_rows
def insert_workrow(values, tab_name='homework'):
# 这里我们只处理输入值数目为5个的情况
if ((not isinstance(values, list)) and (not isinstance(values,tuple))) or len(values)!=5:
raise Exception('type error or length incorrect!!!')
# Connect to the database
connection = pymysql.connect(host=db_config.HOST,
user=db_config.USER,
port=db_config.DB_PORT,
password=db_config.PWD,
database=db_config.DB_NAME,
cursorclass=pymysql.cursors.Cursor)
with connection:
try:
with connection.cursor() as cursor:
# 表格名称不能使用占位符,只能拼接字符串
sql = f"insert into {tab_name} values (%s, %s, %s, %s, %s);"
affected_rows = cursor.execute(sql, values)
# connection is not autocommit by default. So you must commit to save your changes.
connection.commit()
except:
return 0
return affected_rows
if __name__ == '__main__':
results=getData()
print(results)
for row in results:
print(row)
main_gui.py文件里有import FreeSimpleGUI as sg
#需要切换为MySQL数据库,请将fetch_data_mssql更改为:fetch_data_mysql
from fetch_data_mysql import getData, del_row, insert_row,insert_workrow,getData_aim
from db_config import get_header
def open_homework_search():
sublayout_homesearch = [
[sg.T('请输入要查询的学号:', justification='right'),
sg.Input('', size=(50, None), key='-sub_Rname-')],
[sg.Button('查询', key='-btn_search-')]
]
subwin_homeworksearch = sg.Window('搜索', sublayout_homesearch,
font=('微软雅黑', 13), modal=True)
while True:
ev2, dict_vals2 = subwin_homeworksearch.read()
if ev2 in (sg.WIN_CLOSED, 'Exit'):
break
elif ev2 == '-btn_search-':
student_id = dict_vals2['-sub_Rname-'].strip() or None
result = getData_aim(student_id,tab_name='tbcourse')
sg.popup(f"找到{len(result)}条记录" if result else "未找到记录")
break
subwin_homeworksearch.close()
return result if 'result' in locals() else None
def open_rank_system():
layout = [
[sg.T('输入分数:', size=(10,None), justification='right'),
sg.Input('', (20, None), key='-INPUT_SCORE-')],
[sg.T('等级结果:', size=(10,None), justification='right'),
sg.Text('', size=(20,1), key='-OUTPUT_GRADE-')],
[sg.Button('转换', key='-btn_rank_system', size=(10,None))]
]
window = sg.Window('分数等级转换器', layout, font=('微软雅黑', 13))
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == '-btn_rank_system':
try:
score = float(values['-INPUT_SCORE-'])
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'E'
window['-OUTPUT_GRADE-'].update(grade)
except ValueError:
sg.popup_error('请输入有效数字!')
window.close()
def open_hundredsystem():
layout = [
[sg.T('原始数值:', size=(10,None), justification='right'),
sg.Input('', (20, None), key='-INPUT_VALUE-')],
[sg.T('百分制结果:', size=(10,None), justification='right'),
sg.Text('', size=(20,1), key='-OUTPUT_PERCENT-')],
[sg.Button('转换', key='-btn_hundred_system', size=(10,None))]
]
window = sg.Window('百分制转换器', layout, font=('微软雅黑', 13))
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == '-btn_hundred_system':
try:
raw_value = float(values['-INPUT_VALUE-'])
percent_value = raw_value * 0.1 *0.1
window['-OUTPUT_PERCENT-'].update(f"{percent_value:.2f}%")
except ValueError:
sg.popup_error('请输入有效数字!')
window.close()
def open_addHomeworkWindow():
sublayout_homework = [
[sg.T('学号:', size=(None,None), justification='right'), sg.Input('', (50, None), key='-sub_Sno-' )],
[sg.T('姓名:', size=(None,None), justification='right'), sg.Input('', (50, None), key='-sub_Sname-' )],
[sg.T('课后任务:', size=(None,None), justification='right'), sg.Input('', (50, None), key='-sub_Cno-' )],
[sg.T('提交日期:', size=(None,None), justification='right'), sg.Input('', (50, None), key='-sub_Hyime-' )],
[sg.T('评分:', size=(None,None), justification='right'), sg.Input('', (50, None), key='-sub_Grade-' )],
[sg.Ok('发布', key='-btn_sub_addhomework-',size=(10,None))]
]
subwin_addhomework = sg.Window('添加新任务(作业)', sublayout_homework, font=('微软雅黑', 13), modal=True)
add_affected_rows = 0
while True:
ev2, dict_vals2 = subwin_addhomework.Read()
if ev2 == sg.WIN_CLOSED or ev2 == 'Exit':
break
elif ev2 == '-btn_sub_addhomework-':
dict_vals2['-sub_Sno-'] = None if dict_vals2['-sub_Sno-']=='' else dict_vals2['-sub_Sno-']
add_affected_rows = insert_workrow(list(dict_vals2.values()), tab_name='homework')
break
subwin_addhomework.close()
if add_affected_rows>0:
sg.popup_timed('发布成功!')
if add_affected_rows<=0:
sg.popup_timed('发布失败!')
return add_affected_rows
def open_addCourseWindow():
sublayout_course = [
[sg.T('课程号:', size=(10,None), justification='right'), sg.Input('', (50, None), key='-sub_cno-' )],
[sg.T('课程名称:', size=(10,None), justification='right'), sg.Input('', (50, None), key='-sub_cname-' )],
[sg.T('先修课:', size=(10,None), justification='right'), sg.Input('', (50, None), key='-sub_cpno-' )],
[sg.T('学分:', size=(10,None), justification='right'), sg.Input('', (50, None), key='-sub_ccredit-' )],
[sg.Ok('确定', key='-btn_sub_addcourse-',size=(10,None))]
]
subwin_addCourse = sg.Window('添加课程信息', sublayout_course, font=('微软雅黑', 13), modal=True)
add_affected_rows = 0
while True:
ev2, dict_vals2 = subwin_addCourse.Read()
if ev2 == sg.WIN_CLOSED or ev2 == 'Exit':
break
elif ev2 == '-btn_sub_addcourse-':
dict_vals2['-sub_cpno-'] = None if dict_vals2['-sub_cpno-']=='' else dict_vals2['-sub_cpno-']
add_affected_rows = insert_row(list(dict_vals2.values()), tab_name='tbCourse')
break
subwin_addCourse.close()
if add_affected_rows>0:
sg.popup_timed('插入课程信息成功!')
return add_affected_rows
def refreshData(table_key='-TABLE_course-', tab_name='tbcourse'):
# 刷新表的显示
data_courses = getData(tab_name=tab_name)
window[table_key].update(data_courses)
return data_courses
if __name__ == '__main__':
sg.theme('DefaultNoMoreNagging')
data_ducsum = getData(tab_name='ducsum')
header_ducsum = get_header(tab_name='ducsum')
data_homework = getData(tab_name='homework')
header_homework = get_header(tab_name='homework')
data_courses = getData(tab_name='tbcourse')
header_courses = get_header(tab_name='course')
data_students = getData(tab_name='tbStuinfo')
header_students = get_header(tab_name='student')
header_sc = get_header(tab_name='sc')
Alsum_layout = [
[sg.Button(button_text='导入'),sg.Button(button_text='导出')],
[sg.Table(values=data_ducsum,
headings=header_ducsum,
size=(550,400),
max_col_width=100,
auto_size_columns=False,
display_row_numbers=False,
justification='left',
num_rows=15,
alternating_row_color='lightyellow',
key='-TABLE_course-',
selected_row_colors='red on yellow',
enable_events=True,
expand_x=True,
expand_y=True,
enable_click_events=True, # Comment out to not enable header and other clicks
tooltip='This is a course table')
]
]
Grade_layout = [
[sg.Column([
[sg.Text('评分标准模式', justification='center', expand_x=True)],
[sg.Push(), sg.Button('百分制',key='-btn_hundred_system'), sg.Push(), sg.Button('分级制',key='-btn_rank_system'), sg.Push()]
], expand_x=True)]
]
homework_layout = [
[sg.InputText(),sg.Button(button_text='搜索',key='-btn_homework_search'),
sg.Button(button_text='添加',key='-btn_add_homework'),
sg.Button(button_text='删除'),
sg.Button(button_text='修改')
],
[sg.Table(values=data_homework,
headings=header_homework,
size=(550,400),
max_col_width=100,
auto_size_columns=False,
display_row_numbers=False,
justification='left',
num_rows=15,
alternating_row_color='lightyellow',
key='-TABLE_course-',
selected_row_colors='red on yellow',
enable_events=True,
expand_x=True,
expand_y=True,
enable_click_events=True, # Comment out to not enable header and other clicks
tooltip='This is a course table')
],
[sg.Button(button_text='上一页', key='-btn_refresh_course-'),
sg.Button(button_text='下一页', key='-btn_del_course-')
]
]
course_layout = [
[sg.Table(values=data_courses,
headings=header_courses,
size=(550,400),
max_col_width=100,
auto_size_columns=False,
display_row_numbers=False,
justification='left',
num_rows=15,
alternating_row_color='lightyellow',
key='-TABLE_course-',
selected_row_colors='red on yellow',
enable_events=True,
expand_x=True,
expand_y=True,
enable_click_events=True, # Comment out to not enable header and other clicks
tooltip='This is a course table')
],
[sg.Button(button_text='刷新', key='-btn_refresh_course-'),
sg.Button(button_text='删除', key='-btn_del_course-'),
sg.Button(button_text='添加', key='-btn_add_course-')
]
]
student_layout = [
[sg.Table(values=data_students,
headings=header_students,
size=(550, 400),
max_col_width=100,
auto_size_columns=False,
display_row_numbers=False,
justification='left',
num_rows=15,
alternating_row_color='lightyellow',
key='-TABLE_Student-',
selected_row_colors='red on yellow',
enable_events=True,
expand_x=True,
expand_y=True,
enable_click_events=True, # Comment out to not enable header and other clicks
tooltip='This is a student table')
],
[sg.Button(button_text='刷新', key='-btn_refresh_student-'),
sg.Button(button_text='删除', key='-btn_del_student-'),
sg.Button(button_text='添加', key='-btn_add_student-')
]
]
SC_layout = [[sg.Table(values=[[]],
headings=header_sc,
# size=(550, 400),
max_col_width=100,
auto_size_columns=False,
display_row_numbers=False,
justification='left',
num_rows=15,
alternating_row_color='lightyellow',
key='-TABLE_SC-',
selected_row_colors='red on yellow',
enable_events=True,
expand_x=True,
expand_y=True,
enable_click_events=True, # Comment out to not enable header and other clicks
tooltip='This is a SC table')
],
[sg.Button(button_text='刷新', key='-btn_refresh_sc-'),
sg.Button(button_text='删除', key='-btn_del_sc-'),
sg.Button(button_text='添加', key='-btn_add_sc-')
]
]
layout = [[sg.TabGroup([[sg.Tab('首页', homework_layout, key='-tab_homework'),
sg.Tab('设置', Grade_layout,key='-tab_course-'),
sg.Tab('汇总', Alsum_layout,key='-tab_course-'),
sg.Tab('课程表', course_layout, key='-tab_course-'),
sg.Tab('学生表', student_layout, key='-tab_student-'),
sg.Tab('选课表', SC_layout, key='-tab_sc-')]],
key='-group2-', title_color='red',
selected_title_color='green', tab_location='left')
]]
window = sg.Window('课后作业评分系统', layout,
default_element_size=(10, 1),size=(740,580), font=('微软雅黑', 14))
cur_cno=None #当前的选择的课程号
cur_course_row_number=None #当前课程表中被选择的行号,行号从0开始,-1为标题行
subwin_addCourse_active = False
subwin_addCourse = None
while True:
event, values = window.read()
# sg.popup_non_blocking(event, values)
# print(event)
# print(values)
if event == sg.WIN_CLOSED: # always, always give a way out!
break
if event=='-btn_del_course-':
# 删除选择的课程号
aff_rows = del_row(cno=cur_cno, tab_name='tbCourse')
print('影响的行数:', aff_rows)
if(aff_rows>0):
data_courses = list(data_courses)
data_courses.pop(cur_course_row_number) #从数据表格中移除选择的行数据
window['-TABLE_course-'].update(data_courses)
cur_course_row_number = None
cur_cno = None
elif event=='-btn_add_course-':
# 添加课程
# 先弹窗,获取信息
add_affected_rows = open_addCourseWindow()
if add_affected_rows>0:
data_courses = refreshData(table_key='-TABLE_course-', tab_name='tbcourse')
elif event=='-btn_refresh_course-':
# 刷新课程表的显示
data_courses = refreshData(table_key='-TABLE_course-', tab_name='tbcourse')
elif event=='-btn_add_homework':
add_affected_row = open_addHomeworkWindow()
if add_affected_row>0:
data_courses = refreshData(table_key='-TABLE_course-',tab_name='tbcourse')
elif event=='-btn_hundred_system':
add_affected_row = open_hundredsystem()
if add_affected_row>0:
data_courses = refreshData(table_key='-TABLE_course-',tab_name='tbcourse')
elif event=='-btn_rank_system':
add_affected_row = open_rank_system()
if add_affected_row>0:
data_courses = refreshData(table_key='-TABLE_course-',tab_name='tbcourse')
elif event=='-btn_homework_search':
add_affected_row = open_homework_search()
if add_affected_row>0:
data_courses = refreshData(table_key='-TABLE_course-',tab_name='tbcourse')
if isinstance(event, tuple):
# TABLE CLICKED Event has value in format ('-TABLE-', '+CLICKED+', (row,col))
if event[0] == '-TABLE_course-':
cur_course_row_number = event[2][0]
col_number = event[2][1]
if cur_course_row_number is not None:
# 获取鼠标点击行的数据
cur_row_value = data_courses[cur_course_row_number]
# 获取点击行的Cno
cur_cno = cur_row_value[0]
print('当前选择的课程号:', cur_cno)
window.close()
请修正以上代码,使全部代码正常实现功能