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, ('[email protected]',)) 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() 请修正以上代码,使全部代码正常实现功能
时间: 2025-07-31 14:05:54 AIGC 浏览: 20
<think>我们发现了几个问题,需要修正:1.在`fetch_data_mysql.py`中,`getData_aim`函数有一个错误:在SQL语句中,我们使用`whereSNO=%s`,但是执行时传入的参数是`('Sno',)`,这会导致查询失败。应该传入的是`(Sno,)`,即函数的参数。2.在`main_gui.py`中,`open_homework_search`函数里调用`getData_aim`时,传入的`tab_name`为'tbcourse',但是作业表名应该是'homework'。而且,在搜索作业时,应该查询作业表,而不是课程表。3.在`main_gui.py`中,多个表格使用了相同的key(`-TABLE_course-`),这会导致事件处理混乱。我们需要为每个表格设置唯一的key。4.在`main_gui.py`中,删除课程后,我们直接从当前显示的列表数据中移除一行,但这样可能会和数据库不一致(如果其他用户修改了数据)。更好的做法是删除后重新从数据库加载。5.在`main_gui.py`中,事件处理部分,对于作业的添加、删除、修改等操作后,刷新的是课程表(`-TABLE_course-`),但实际上应该刷新作业表。6.在`main_gui.py`中,布局定义部分,多个标签页的表格key重复,我们需要修改为不同的key。7.在`main_gui.py`中,作业管理标签页的表格key是`-TABLE_course-`,应该改为`-TABLE_HOMEWORK-`之类的唯一key。8.在`main_gui.py`中,事件`-btn_add_homework`的绑定事件代码中,事件名缺少一个下划线(应该是`-btn_add_homework-`)。9.在`main_gui.py`中,作业搜索窗口的输入框key是`-sub_Rname-`,应该改为更合适的名字,比如`-sub_Sno-`,并在获取值时注意。我们将逐一修正这些问题。第一步:修正`fetch_data_mysql.py`中的`getData_aim`函数。将:cursor.execute(sql,('Sno',))改为:cursor.execute(sql,(Sno,))第二步:在`main_gui.py`中,修改`open_homework_search`函数,将查询的表名改为'homework',并且确保传入的学号正确。第三步:修改布局,为每个表格设置唯一的key:-汇总表(Alsum_layout)的表格key改为:`-TABLE_SUMMARY-`-作业管理(homework_layout)的表格key改为:`-TABLE_HOMEWORK-`-课程表(course_layout)的表格key改为:`-TABLE_COURSE-`-学生表(student_layout)的表格key改为:`-TABLE_STUDENT-`-选课表(SC_layout)的表格key改为:`-TABLE_SC-`第四步:在事件处理中,针对不同的操作刷新对应的表格。例如,删除课程后刷新课程表,添加作业后刷新作业表。第五步:修正事件绑定,特别是作业添加按钮的事件名。第六步:在作业搜索窗口中,将输入框的key改为`-sub_Sno-`,并在读取时使用这个key。由于代码较长,我们只给出修改后的关键部分。修改后的`fetch_data_mysql.py`中`getData_aim`函数:</think>我将修正代码中的关键问题,确保所有功能正常运行。以下是完整的修复版本:
### 修复后的 `fetch_data_mysql.py`
```python
import pymysql.cursors
import db_config
def getData(tab_name='tbcourse'):
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:
with connection.cursor() as cursor:
sql = f"SELECT * FROM {tab_name};"
cursor.execute(sql)
results = cursor.fetchall()
return results
def getData_aim(Sno, tab_name='homework'):
"""根据学号查询特定学生的作业数据"""
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:
with connection.cursor() as cursor:
# 修复SQL语句中的问题:使用正确的列名和参数
sql = f"SELECT * FROM {tab_name} WHERE Sno=%s;"
cursor.execute(sql, (Sno,)) # 传递正确的参数
results = cursor.fetchall()
return results
def del_row(value, tab_name='tbCourse', col_name='Cno'):
"""删除指定行数据"""
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 {col_name}=%s;"
affected_rows = cursor.execute(sql, (value,))
connection.commit()
except Exception as e:
print(f"删除错误: {e}")
return 0
return affected_rows
def insert_row(values, tab_name='tbCourse'):
if (not isinstance(values, (list, tuple))) or len(values) != 4:
raise Exception('类型错误或长度不正确!!!')
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.commit()
except Exception as e:
print(f"插入错误: {e}")
return 0
return affected_rows
def insert_workrow(values, tab_name='homework'):
if (not isinstance(values, (list, tuple))) or len(values) != 5:
raise Exception('类型错误或长度不正确!!!')
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.commit()
except Exception as e:
print(f"插入作业错误: {e}")
return 0
return affected_rows
if __name__ == '__main__':
results = getData()
print(results)
for row in results:
print(row)
```
### 修复后的 `main_gui.py`
```python
import FreeSimpleGUI as sg
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_Sno-')],
[sg.Button('查询', key='-btn_search-')]
]
subwin_homeworksearch = sg.Window('搜索作业', sublayout_homesearch,
font=('微软雅黑', 13), modal=True)
result = None
while True:
ev2, vals2 = subwin_homeworksearch.read()
if ev2 in (sg.WIN_CLOSED, 'Exit'):
break
elif ev2 == '-btn_search-':
student_id = vals2['-sub_Sno-'].strip()
if student_id:
result = getData_aim(student_id, tab_name='homework') # 查询作业表
sg.popup(f"找到{len(result)}条记录" if result else "未找到记录")
else:
sg.popup("请输入学号")
subwin_homeworksearch.close()
return result
def open_rank_system():
layout = [
[sg.T('输入分数:'), sg.Input('', key='-INPUT_SCORE-')],
[sg.T('等级结果:'), sg.Text('', size=(10, 1), key='-OUTPUT_GRADE-')],
[sg.Button('转换', key='-btn_convert-')]
]
window = sg.Window('分数等级转换器', layout, font=('微软雅黑', 13))
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == '-btn_convert-':
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('原始分数:'), sg.Input('', key='-INPUT_VALUE-')],
[sg.T('百分制:'), sg.Text('', size=(10, 1), key='-OUTPUT_PERCENT-')],
[sg.Button('转换', key='-btn_convert-')]
]
window = sg.Window('百分制转换器', layout, font=('微软雅黑', 13))
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == '-btn_convert-':
try:
raw_value = float(values['-INPUT_VALUE-'])
percent_value = raw_value * 10 # 假设原始是0-10分,转换为百分制
window['-OUTPUT_PERCENT-'].update(f"{percent_value:.1f}%")
except ValueError:
sg.popup_error('请输入有效数字!')
window.close()
def open_addHomeworkWindow():
sublayout_homework = [
[sg.T('学号:'), sg.Input('', key='-sub_Sno-')],
[sg.T('姓名:'), sg.Input('', key='-sub_Sname-')],
[sg.T('课程号:'), sg.Input('', key='-sub_Cno-')],
[sg.T('提交日期:'), sg.Input('', key='-sub_Hyime-')],
[sg.T('评分:'), sg.Input('', key='-sub_Grade-')],
[sg.Button('发布', key='-btn_submit-')]
]
subwin = sg.Window('添加作业', sublayout_homework, font=('微软雅黑', 13), modal=True)
add_affected_rows = 0
while True:
event, values = subwin.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == '-btn_submit-':
vals = [
values['-sub_Sno-'],
values['-sub_Sname-'],
values['-sub_Cno-'],
values['-sub_Hyime-'],
values['-sub_Grade-']
]
add_affected_rows = insert_workrow(vals)
break
subwin.close()
if add_affected_rows > 0:
sg.popup('发布成功!')
else:
sg.popup('发布失败!')
return add_affected_rows
def open_addCourseWindow():
sublayout_course = [
[sg.T('课程号:'), sg.Input('', key='-sub_cno-')],
[sg.T('课程名称:'), sg.Input('', key='-sub_cname-')],
[sg.T('先修课:'), sg.Input('', key='-sub_cpno-')],
[sg.T('学分:'), sg.Input('', key='-sub_ccredit-')],
[sg.Button('确定', key='-btn_submit-')]
]
subwin = sg.Window('添加课程', sublayout_course, font=('微软雅黑', 13), modal=True)
add_affected_rows = 0
while True:
event, values = subwin.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == '-btn_submit-':
vals = [
values['-sub_cno-'],
values['-sub_cname-'],
values['-sub_cpno-'] or None,
values['-sub_ccredit-']
]
add_affected_rows = insert_row(vals)
break
subwin.close()
if add_affected_rows > 0:
sg.popup('添加成功!')
else:
sg.popup('添加失败!')
return add_affected_rows
def refreshData(table_key, tab_name):
"""刷新表格数据"""
data = getData(tab_name=tab_name)
window[table_key].update(data)
return data
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')
data_sc = getData(tab_name='sc')
# 布局定义 - 为每个表格使用唯一的key
Alsum_layout = [
[sg.Button('导入'), sg.Button('导出')],
[sg.Table(
values=data_ducsum,
headings=header_ducsum,
auto_size_columns=True,
display_row_numbers=True,
justification='left',
num_rows=10,
alternating_row_color='lightyellow',
key='-TABLE_SUMMARY-',
expand_x=True,
expand_y=True
)]
]
Grade_layout = [
[sg.Text('评分标准转换', font=('微软雅黑', 16), justification='center')],
[sg.VPush()],
[sg.Column([
[sg.Push(), sg.Button('百分制转换', key='-btn_hundred_system', size=(15, 2)),
sg.Push(), sg.Button('等级制转换', key='-btn_rank_system', size=(15, 2)), sg.Push()]
], expand_x=True)],
[sg.VPush()]
]
homework_layout = [
[
sg.Input(key='-INPUT_HOMEWORK_SEARCH-', size=(30, 1)),
sg.Button('搜索', key='-btn_homework_search'),
sg.Button('添加', key='-btn_add_homework-'), # 修正事件名称
sg.Button('删除', key='-btn_del_homework'),
sg.Button('修改', key='-btn_edit_homework')
],
[sg.Table(
values=data_homework,
headings=header_homework,
auto_size_columns=True,
display_row_numbers=True,
justification='left',
num_rows=10,
alternating_row_color='lightyellow',
key='-TABLE_HOMEWORK-', # 唯一key
expand_x=True,
expand_y=True,
enable_events=True
)],
[sg.Button('上一页'), sg.Button('下一页')]
]
course_layout = [
[sg.Table(
values=data_courses,
headings=header_courses,
auto_size_columns=True,
display_row_numbers=True,
justification='left',
num_rows=10,
alternating_row_color='lightyellow',
key='-TABLE_COURSE-', # 唯一key
expand_x=True,
expand_y=True,
enable_events=True
)],
[
sg.Button('刷新', key='-btn_refresh_course-'),
sg.Button('删除', key='-btn_del_course-'),
sg.Button('添加', key='-btn_add_course-')
]
]
student_layout = [
[sg.Table(
values=data_students,
headings=header_students,
auto_size_columns=True,
display_row_numbers=True,
justification='left',
num_rows=10,
alternating_row_color='lightyellow',
key='-TABLE_STUDENT-', # 唯一key
expand_x=True,
expand_y=True,
enable_events=True
)],
[
sg.Button('刷新', key='-btn_refresh_student-'),
sg.Button('删除', key='-btn_del_student-'),
sg.Button('添加', key='-btn_add_student-')
]
]
SC_layout = [
[sg.Table(
values=data_sc,
headings=header_sc,
auto_size_columns=True,
display_row_numbers=True,
justification='left',
num_rows=10,
alternating_row_color='lightyellow',
key='-TABLE_SC-', # 唯一key
expand_x=True,
expand_y=True,
enable_events=True
)],
[
sg.Button('刷新', key='-btn_refresh_sc-'),
sg.Button('删除', key='-btn_del_sc-'),
sg.Button('添加', key='-btn_add_sc-')
]
]
# 标签页布局
layout = [
[sg.TabGroup([
[
sg.Tab('首页', homework_layout, key='-tab_homework'),
sg.Tab('设置', Grade_layout, key='-tab_grade'),
sg.Tab('汇总', Alsum_layout, key='-tab_summary'),
sg.Tab('课程表', course_layout, key='-tab_course'),
sg.Tab('学生表', student_layout, key='-tab_student'),
sg.Tab('选课表', SC_layout, key='-tab_sc')
]
], key='-TAB_GROUP-', tab_location='left', title_color='red', selected_title_color='green')]
]
window = sg.Window('课后作业评分系统', layout, font=('微软雅黑', 14), size=(740, 580))
# 当前选择的数据
current_selection = {
'course': {'row': None, 'cno': None},
'homework': {'row': None, 'sno': None},
'student': {'row': None, 'sno': None},
'sc': {'row': None}
}
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
# 刷新数据
if event == '-btn_refresh_course-':
data_courses = refreshData('-TABLE_COURSE-', 'tbcourse')
elif event == '-btn_refresh_student-':
data_students = refreshData('-TABLE_STUDENT-', 'tbStuinfo')
elif event == '-btn_refresh_homework-':
data_homework = refreshData('-TABLE_HOMEWORK-', 'homework')
elif event == '-btn_refresh_sc-':
data_sc = refreshData('-TABLE_SC-', 'sc')
# 课程删除
elif event == '-btn_del_course-':
if current_selection['course']['row'] is not None:
cno = current_selection['course']['cno']
if cno:
aff_rows = del_row(cno, 'tbCourse', 'Cno')
if aff_rows > 0:
sg.popup(f'成功删除课程 {cno}')
data_courses = refreshData('-TABLE_COURSE-', 'tbcourse')
else:
sg.popup('删除失败')
else:
sg.popup('请先选择课程')
else:
sg.popup('请先选择课程')
# 添加课程
elif event == '-btn_add_course-':
add_affected_rows = open_addCourseWindow()
if add_affected_rows > 0:
data_courses = refreshData('-TABLE_COURSE-', 'tbcourse')
# 添加作业
elif event == '-btn_add_homework-': # 修正事件名称
add_affected_rows = open_addHomeworkWindow()
if add_affected_rows > 0:
data_homework = refreshData('-TABLE_HOMEWORK-', 'homework')
# 分数转换功能
elif event == '-btn_hundred_system-':
open_hundredsystem()
elif event == '-btn_rank_system-':
open_rank_system()
# 作业搜索
elif event == '-btn_homework_search-':
search_text = values['-INPUT_HOMEWORK_SEARCH-'].strip()
if search_text:
result = getData
阅读全文
相关推荐












