如何在PySimpleGUI网格中定位已选中的矩形?
实现获取所有选中矩形的方法
首先,你需要先把所有网格矩形的ID存起来,方便后续遍历检查。下面是完整的示例代码,整合了5×5网格、拖拽选中高亮,以及点击按钮获取选中项的功能:
import PySimpleGUI as sg # 定义颜色常量 HIGHLIGHT_COLOR = '#90EE90' # 淡绿色高亮 DEFAULT_COLOR = 'white' # 默认填充色 GRID_SIZE = 5 # 网格大小 CELL_SIZE = 50 # 每个单元格尺寸 # 创建布局 layout = [ [sg.Graph((GRID_SIZE*CELL_SIZE, GRID_SIZE*CELL_SIZE), (0, 0), (GRID_SIZE*CELL_SIZE, GRID_SIZE*CELL_SIZE), key='-GRAPH-')], [sg.Button('获取选中矩形', key='-GET_SELECTED-'), sg.Text('', key='-RESULT-')] ] window = sg.Window('网格选中示例', layout, finalize=True) graph = window['-GRAPH-'] # 存储所有矩形的ID,二维列表对应网格位置 rect_ids = [] for i in range(GRID_SIZE): row_ids = [] for j in range(GRID_SIZE): x1 = j * CELL_SIZE y1 = i * CELL_SIZE x2 = x1 + CELL_SIZE y2 = y1 + CELL_SIZE # 绘制矩形并保存ID rect_id = graph.draw_rectangle((x1, y1), (x2, y2), fill_color=DEFAULT_COLOR, line_color='black') row_ids.append(rect_id) rect_ids.append(row_ids) # 拖拽选中相关变量 dragging = False selected_start = None while True: event, values = window.read() if event == sg.WIN_CLOSED: break # 处理鼠标点击/拖拽选中 if event == '-GRAPH-': x, y = values['-GRAPH-'] # 计算点击的单元格坐标 cell_x = int(x // CELL_SIZE) cell_y = int(y // CELL_SIZE) # 确保坐标在网格范围内 if 0 <= cell_x < GRID_SIZE and 0 <= cell_y < GRID_SIZE: if not dragging: # 开始拖拽,记录起始位置 dragging = True selected_start = (cell_y, cell_x) # 先高亮当前点击的单元格 graph.itemconfig(rect_ids[cell_y][cell_x], fill_color=HIGHLIGHT_COLOR) else: # 拖拽过程中,计算选中的矩形范围 start_y, start_x = selected_start end_y, end_x = cell_y, cell_x # 确定范围的上下左右 min_y = min(start_y, end_y) max_y = max(start_y, end_y) min_x = min(start_x, end_x) max_x = max(start_x, end_x) # 先重置所有单元格颜色 for i in range(GRID_SIZE): for j in range(GRID_SIZE): graph.itemconfig(rect_ids[i][j], fill_color=DEFAULT_COLOR) # 高亮选中范围内的单元格 for i in range(min_y, max_y+1): for j in range(min_x, max_x+1): graph.itemconfig(rect_ids[i][j], fill_color=HIGHLIGHT_COLOR) else: # 点击到网格外,结束拖拽 dragging = False selected_start = None # 鼠标释放时结束拖拽 elif event == '-GRAPH-+UP': dragging = False # 处理获取选中矩形的按钮点击 elif event == '-GET_SELECTED-': selected_cells = [] # 遍历所有矩形ID,检查填充色 for i in range(GRID_SIZE): for j in range(GRID_SIZE): current_color = graph.itemcget(rect_ids[i][j], 'fill') if current_color == HIGHLIGHT_COLOR: # 记录单元格位置(可以换成ID或者其他信息) selected_cells.append(f'({i+1}, {j+1})') # 转换成1-based索引方便查看 # 更新结果文本 if selected_cells: window['-RESULT-'].update(f'选中的矩形位置:{",".join(selected_cells)}') else: window['-RESULT-'].update('没有选中任何矩形') window.close()
关键步骤说明:
- 存储矩形ID:绘制网格时,把每个矩形的ID存入二维列表
rect_ids,对应网格的行和列,方便后续精准定位每个单元格。 - 用
itemcget检查颜色:点击按钮时,遍历rect_ids,调用graph.itemcget(rect_id, 'fill')获取当前填充色,和高亮色对比,匹配的就是选中的矩形。 - 收集结果:把选中的单元格位置(或ID)收集起来,展示到界面上。
你可以直接运行这段代码测试功能,如果原有代码结构不同,只需把存储ID和检查颜色的逻辑对应到自己的代码里即可。
内容的提问来源于stack exchange,提问作者Neil E
相关产品推荐
相关产品推荐

