在Visual Studio Code中使用matplotlib显示图形时,图形没有响应,错误信息如下:无法为'qt'启用GUI事件循环集成Traceback(大多数记录)...
在Visual Studio Code中使用matplotlib显示图形时,图形无响应,错误信息如下:
Failed to enable GUI event loop integration for 'qt'
Traceback (most recent call last):
File "~\.vscode\extensions\ms-python.debugpy-2024.8.0-win32-x64\bundled\libs\debugpy\_vendored\pydevd\pydev_ipython\matplotlibtools.py", line 30, in do_enable_gui
enable_gui(guiname)
File "~\.vscode\extensions\ms-python.debugpy-2024.8.0-win32-x64\bundled\libs\debugpy\_vendored\pydevd\pydev_ipython\inputhook.py", line 540, in enable_gui
return gui_hook(app)
^^^^^^^^^^^^^
File "~\.vscode\extensions\ms-python.debugpy-2024.8.0-win32-x64\bundled\libs\debugpy\_vendored\pydevd\pydev_ipython\inputhook.py", line 176, in enable_qt
from pydev_ipython.qt_for_kernel import QT_API, QT_API_PYQT5
File "~\.vscode\extensions\ms-python.debugpy-2024.8.0-win32-x64\bundled\libs\debugpy\_vendored\pydevd\pydev_ipython\qt_for_kernel.py", line 116, in <module>
QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts)
^^^^^^^^^^^^^^^^^
File "~\.vscode\extensions\ms-python.debugpy-2024.8.0-win32-x64\bundled\libs\debugpy\_vendored\pydevd\pydev_ipython\qt_loaders.py", line 276, in load_qt
if not can_import(api):
^^^^^^^^^^^^^^^
File "~\.vscode\extensions\ms-python.debugpy-2024.8.0-win32-x64\bundled\libs\debugpy\_vendored\pydevd\pydev_ipython\qt_loaders.py", line 152, in can_import
if not has_binding(api):
^^^^^^^^^^^^^^^^
File "~\.vscode\extensions\ms-python.debugpy-2024.8.0-win32-x64\bundled\libs\debugpy\_vendored\pydevd\pydev_ipython\qt_loaders.py", line 115, in has_binding
import imp
ModuleNotFoundError: No module named 'imp'
Backend QtAgg is interactive backend. Turning interactive mode on.
我的代码如下(原代码经过了处理,能触发这个Bug的代码如下):
import torch
import matplotlib.pyplot as plt
def main():
data = torch.arange(1, 10)
plt.plot(data)
plt.title('label name')
# ……
if __name__ == '__main__':
main()
使用的时候 plt.ion()
不起作用。
这可能是由于 matplotlib 后端设置不正确。在我的代码中将 matplotlib 后端设置为“TkAgg”,这通常是最广泛支持的图形后端。
我在我的代码中尝试了这个并且成功了,这可能是由 vscode 错误引起的:
import matplotlib
matplotlib.use('TkAgg')
plt.ion()
总代码如下:
import torch
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
plt.ion()
def main():
data = torch.arange(1, 10)
plt.plot(data)
plt.title('label name')
# ……
if __name__ == '__main__':
main()