Python pyplot绘图阻塞while循环无法接收用户输入Bug排查
问题根因
你遇到的阻塞问题来自matplotlib默认的运行模式:plt.show()默认采用阻塞式调用,会占用当前Python主线程的事件循环,直到所有打开的matplotlib窗口被手动关闭,才会继续执行后续代码,因此你的while循环会卡在绘图步骤,无法继续接收用户输入。
另外你贴的复现代码存在缩进错误:while True:下方的所有逻辑没有缩进,直接运行会触发语法报错。
修复方案
不需要关闭窗口就能继续接收输入的核心是开启matplotlib的交互模式,替换阻塞式的绘图调用:
- 导入pyplot后第一时间调用
plt.ion()开启全局交互模式,该模式下绘图操作不会阻塞主线程 - 将阻塞的
plt.show()替换为plt.draw()触发图形渲染,搭配plt.pause(0.1)给GUI渲染留出短暂缓冲时间,避免图形加载不全 - 可选优化:复用同一个绘图窗口,每次选新路线时清空画布重绘,避免每次绘图都弹出新窗口堆积。
修复后完整代码
from matplotlib import pyplot as plt # 开启交互模式,取消绘图阻塞 plt.ion() route001 = (3, 12, 'S', 'S', 'W', 'S', 'S', 'S', 'E', 'E', 'E', 'S', 'S', 'W', 'W', 'S', 'E', 'E', 'E', 'E', 'N', 'N', 'N', 'N', 'W', 'N', 'N', 'E', 'E', 'S', 'E', 'S', 'E', 'S', 'S', 'W', 'S', 'S', 'S', 'S', 'S', 'E', 'N', 'E', 'E') route002 = (12, 11, 'W', 'W', 'S', 'S', 'S', 'W', 'W', 'N', 'N', 'N', 'W', 'W', 'W', 'S', 'S', 'S', 'S', 'E', 'E', 'S', 'W', 'W', 'W', 'W', 'N', 'N', 'W', 'W', 'S', 'S', 'S', 'S', 'E', 'E', 'E', 'S', 'E', 'S', 'E', 'S') route003 = (3, 12, 'S', 'S', 'W', 'S', 'S', 'S', 'W', 'W', 'W', 'S', 'S', 'W', 'W', 'S', 'E', 'E', 'E', 'E', 'N', 'N', 'N', 'N', 'W', 'N', 'N', 'E', 'E', 'S', 'E', 'S', 'E', 'S', 'S', 'W', 'S', 'S', 'S', 'S', 'S', 'E', 'N', 'E', 'E') # 提前创建复用的绘图窗口,避免重复弹窗 fig, ax = plt.subplots() while True: # 修复原代码的缩进问题 route_selection = input('Select route 1, 2 or 3 ') if route_selection == "1": selectedRoute = route001 elif route_selection == "2": selectedRoute = route002 elif route_selection == "3": selectedRoute = route003 else: print("error, please input 1, 2 or 3") continue start = [selectedRoute[0]] + [selectedRoute[1]] directions = selectedRoute[2:] coordinates = {"N": [0, 1], 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0]} vector_list = [] for d in directions: dx, dy = coordinates[d] start[0] += dx start[1] += dy if start[0] < 0 or start[0] > 12: print('Error: This route goes outside the grid') break elif start[1] < 0 or start[1] > 12: print('Error: This route goes outside the grid') break else: print(start) vector_list.append(start.copy()) if not vector_list: continue start_route = vector_list[0] end_route = vector_list[-1] # 清空上次的绘图内容 ax.clear() x = [p[0] for p in vector_list] y = [p[1] for p in vector_list] ax.set_xticks(range(13)) ax.set_yticks(range(13)) ax.plot(x, y, 'o-', color='blue') ax.grid() ax.set_xlim(0,12) ax.set_ylim(0,12) ax.text(start_route[0], start_route[1], " START") ax.text(end_route[0], end_route[1], ' END') ax.set_title('Drone Route') # 非阻塞渲染 plt.draw() plt.pause(0.1)
效果说明
运行代码后,每次输入路线编号,绘图窗口会自动更新为对应路线,不需要手动关闭窗口,终端会立刻回到等待输入的状态,支持连续选择不同路线查看。
内容的提问来源于stack exchange,提问作者robbo500
相关产品推荐
相关产品推荐

