IT일지/파이썬

[파이썬] Pyqt5 mplfinance 차트 출력 시 발생하는 The event loop is already running 경고 메시지 처리하기

체험가 2024. 2. 9. 18:27
반응형

 

pyqt5와 mplfinance를 이용하여 위와같이 버튼을 누르면 캔들차트를 출력하는 간단한 프로그램을 테스트 하던 중 발생한 에러는 아니고 경고 메시지입니다.

QCoreApplication::exec: The event loop is already running

 

사용한 코드는 다음과 같습니다.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
import mplfinance as mpf
import pandas as pd

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Candlestick Chart Example")

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.layout = QVBoxLayout(self.central_widget)

        self.button = QPushButton("Show Candlestick Chart")
        self.layout.addWidget(self.button)

        self.button.clicked.connect(self.show_candlestick_chart)

    def show_candlestick_chart(self):
        data = {
            'Date': pd.date_range(start='2024-01-01', periods=10),
            'Open': [100, 110, 120, 130, 140, 150, 160, 170, 180, 190],
            'High': [105, 115, 125, 135, 145, 155, 165, 175, 185, 195],
            'Low': [95, 105, 115, 125, 135, 145, 155, 165, 175, 185],
            'Close': [102, 112, 122, 132, 142, 152, 162, 172, 182, 192],
            'Volume': [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900]
        }

        df = pd.DataFrame(data)
        df.set_index('Date', inplace=True)

        mpf.plot(df, type='candle')

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

 


원인

이벤트 루프가 이미 실행중이라는 에러 메시지에서 유추해 볼 수 있는 상황은 Pyqt5 애플리케이션이 실행 될 때 QApplication에서 이미 이벤트 루프실행시켜놨는데 mlpfinance에서 차트를 그리면서 이벤트 루프를 새로 실행하려는 것으로 추측해볼 수 있습니다.

 

참고로 이벤트 루프(Event Loop)는 GUI 프로그램에서 사용자 입력 및 시스템 이벤트를 처리하는 핵심 메커니즘으로 사용자 입력(마우스 클릭, 키보드 입력 등) 및 시스템 이벤트(타이머, 소켓 통신)를 대기하고 이벤트를 처리하는 동작을 합니다.


해결방법

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import mplfinance as mpf
import pandas as pd

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Candlestick Chart Example")

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.layout = QVBoxLayout(self.central_widget)

        self.button = QPushButton("Show Candlestick Chart")
        self.layout.addWidget(self.button)

        self.button.clicked.connect(self.show_candlestick_chart)

    def show_candlestick_chart(self):
        data = {
            'Date': pd.date_range(start='2024-01-01', periods=10),
            'Open': [100, 110, 120, 130, 140, 150, 160, 170, 180, 190],
            'High': [105, 115, 125, 135, 145, 155, 165, 175, 185, 195],
            'Low': [95, 105, 115, 125, 135, 145, 155, 165, 175, 185],
            'Close': [102, 112, 122, 132, 142, 152, 162, 172, 182, 192],
            'Volume': [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900]
        }

        df = pd.DataFrame(data)
        df.set_index('Date', inplace=True)

        figure = Figure()
        canvas = FigureCanvas(figure)
        main_ax = figure.add_subplot(111)

        mpf.plot(df, type='candle', ax=main_ax)

        canvas.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

 

바뀐 부분을 보면 위에서 

mpf.plot(df, type='candle')

 

였던 부분을 필요한 라이브러리를 추가하고

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
        figure = Figure()
        canvas = FigureCanvas(figure)
        main_ax = figure.add_subplot(111)

        mpf.plot(df, type='candle', ax=main_ax)

        canvas.show()

이렇게 바꿔줬습니다.

 

mpf로 개별적인 창을 띄워서 그래프를 출력하려고 했던 위쪽 코드와 다르게

해결방법에서는 mpf를 위젯으로 만들어 동작하게 하였습니다.

 

이렇게 하면 mpf가 그리는 차트도 하나의 위젯으로 취급해서 새로운 이벤트 루프를 실행하지 않으니 
QCoreApplication::exec: The event loop is already running 메시지도 발생하지 않았습니다.

 

사실 해당 메시지는 출력되어도 큰 문제가 발생하지 않지만, 만약 프로그램이 예상대로 동작하지 않는 경우 이러한 경고 메시지가 원인일 수도 있으므로 원인을 찾아 해결해두면 나중이 편할 수 있습니다.

728x90
반응형