file-type

Ruby课程作业解析与实践指南

ZIP文件

下载需积分: 9 | 15KB | 更新于2025-09-06 | 57 浏览量 | 0 下载量 举报 收藏
download 立即下载
标题:“a-A_Homework”表明了这是一份关于App Academy家庭作业的内容,App Academy是一所专注于全栈开发训练的教育机构,通过实际的编码练习帮助学生掌握编程技能。 描述:“App Academy家庭作业”强调了这是由App Academy布置的编程练习。家庭作业是学习过程中的重要环节,通过解决实际问题巩固和深化理论知识,并提高解决问题的能力。对于编程学习来说,家庭作业通常包括编写代码、调试程序、实现特定功能等内容。 标签:“Ruby”说明了家庭作业涉及的主要编程语言是Ruby。Ruby是一种高级的动态编程语言,由松本行弘发明,以简洁和高效著称。Ruby的语法清晰、直观,非常适合初学者学习。此外,Ruby的解释器Ruby MRI和Web框架Ruby on Rails都是目前广泛使用的工具。 由于压缩包子文件的文件名称列表仅给出了“a-A_Homework-main”,这可能是压缩包内文件的目录结构。在软件开发中,“main”通常代表主分支或主程序,因此该名称暗示了这个文件是整个家庭作业项目的主要部分,或者是家庭作业中的主程序。 从这些信息中,我们可以总结以下知识点: 1. App Academy编程训练 App Academy是一所专业的软件开发训练学校,它通过一系列的项目和练习帮助学生提高编程能力。家庭作业是App Academy课程中不可或缺的一部分,它帮助学生在真实环境中应用所学知识。 2. 编程家庭作业的重要性 家庭作业在任何编程课程中都占有重要地位。它不仅能够帮助学生复习课堂上讲解的知识点,而且还能通过实践提高学生的编码能力,加强逻辑思维和解决问题的能力。 3. Ruby编程语言 Ruby是一种面向对象的编程语言,特别适合Web应用的开发。它强调简洁和可读性,有一套丰富的内置库,能够快速实现各种功能。Ruby的语法灵活,能够让开发者以更少的代码完成更多的任务。 4. 使用Ruby进行Web开发 Ruby on Rails是基于Ruby的开源Web应用框架,它遵循MVC(模型-视图-控制器)架构,简化了数据库驱动的网站的创建和开发。Ruby on Rails被广泛应用于快速开发动态的Web应用程序。 5. 项目文件结构 在软件项目开发中,文件的命名和组织结构至关重要,它影响到代码的可维护性和项目的可扩展性。常见的项目结构包括分离出主文件、库文件、配置文件以及资源文件等。通过合理的目录划分,可以使得项目结构清晰,方便团队协作和代码版本控制。 6. 编码规范和标准 在进行编程家庭作业时,编码规范和标准是不容忽视的。遵循一定的编码规范不仅可以提高代码的可读性,还可以在团队合作中保持一致性,减少沟通成本。Ruby社区也有一套广泛接受的编码规范,比如Ruby的命名规则、注释和文档的标准等。 综上所述,从这份标题为“a-A_Homework”,描述为“App Academy家庭作业”,标签为“Ruby”,且文件名称列表为“a-A_Homework-main”的文件中,我们可以了解到App Academy的课程布置方式、Ruby编程语言的学习要点以及编程家庭作业的相关知识点。

相关推荐

filetype

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根据上述函数,修改一下代码使之可以实现删除数据的功能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_delet(): """打开删除作业数据的窗口""" sublayout_homedelete = [ [sg.T('请输入要删除的学号:', justification='right'), sg.Input('', size=(50, None), key='-sub_Sno-')], [sg.Button('查询', key='-btn_homework_search-'), sg.Button('确认删除', key='-btn_homework_delet', disabled=True)] ] subwin_homeworkdelete = sg.Window('数据删除', sublayout_homedelete, font=('微软雅黑', 13), modal=True) result = None while True: ev2, vals2 = subwin_homeworkdelete.read() if ev2 in (sg.WIN_CLOSED, 'Exit'): break elif ev2 == '-btn_homework_search-': student_id = vals2['-sub_Sno-'].strip() if not student_id: sg.popup("请输入学号") continue # 查询该学号的作业记录 result = getData_aim(student_id, tab_name='homework') if result: # 显示查询结果 headers = get_header(tab_name='homework') table_layout = [ [sg.Table( values=result, headings=headers, auto_size_columns=True, display_row_numbers=True, justification='left', num_rows=min(5, len(result)), key='-RESULT_TABLE-' )], [sg.Text(f"找到 {len(result)} 条记录,确认删除吗?")] ] # 启用删除按钮 subwin_homeworkdelete['-btn_homework_delet'].update(disabled=False) # 添加结果表格 if hasattr(subwin_homeworkdelete, 'result_frame'): subwin_homeworkdelete['-RESULT_FRAME-'].update(visible=True) subwin_homeworkdelete['-RESULT_TABLE-'].update(result) else: frame = sg.Frame('查询结果', table_layout, key='-RESULT_FRAME-') subwin_homeworkdelete.extend_layout(sublayout_homedelete, [[frame]]) else: sg.popup("未找到相关记录") if hasattr(subwin_homeworkdelete, 'result_frame'): subwin_homeworkdelete['-RESULT_FRAME-'].update(visible=False) subwin_homeworkdelete['-btn_delete-'].update(disabled=True) elif ev2 == '-btn_homework_delet' and result: # 确认删除 if sg.popup_yes_no('确定要删除这些记录吗?此操作不可恢复!') == 'Yes': # 执行删除操作 affected_rows = del_row(vals2['-sub_Sno-'], tab_name='homework', col_name='Sno') if affected_rows > 0: sg.popup(f"成功删除 {affected_rows} 条记录") result = None subwin_homeworkdelete['-RESULT_FRAME-'].update(visible=False) subwin_homeworkdelete['-btn_delete-'].update(disabled=True) else: sg.popup("删除失败,请重试") subwin_homeworkdelete.close()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') homework_layout = [ [sg.InputText(),sg.Button(button_text='搜索',key='-btn_homework_search'), sg.Button(button_text='添加',key='-btn_add_homework'), sg.Button(button_text='删除',key='-btn_homework_delet'), 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-') ] ]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') elif event=='-btn_homework_delet': add_affected_row = open_homework_delet() 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()

filetype

db_config.py里有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(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 department = 'Sno';" # cursor.execute(sql, ('[email protected]',)) cursor.execute(sql) 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这里和fetch.data.mysql里的问题一样连一起 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-')] # 修正2:添加缺失的查询按钮 ] subwin_homeworksearch = sg.Window('搜索', sublayout_homesearch, font=('微软雅黑', 13), modal=True) while True: ev2, dict_vals2 = subwin_homeworksearch.read() # 修正4:read()应小写 if ev2 in (sg.WIN_CLOSED, 'Exit'): break elif ev2 == '-btn_search-': # 修正5:匹配正确的按钮key student_id = dict_vals2['-sub_Rname-'].strip() or None # 修正6:实际执行查询逻辑(原代码直接获取全部数据) result = search_homework_by_student(student_id) 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() 根据上述代码修改优化,使代码能成功运行,实现功能

filetype

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() 请修正以上代码,使全部代码正常实现功能