Python Forum
[PyQt] PyQt5 window closing when trying to display a graph
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyQt] PyQt5 window closing when trying to display a graph
#1
I am developing a GUI Application using PyQt5.

There is a tab with charts and the idea is when clicking a button, it displays a chart.

The following code works just fine:

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import plotly.graph_objects as go
import pandas as pd

class CandlestickTab(QtWidgets.QWidget):
           def __init__(self, parent=None):
        super().__init__(parent)
        self.button = QtWidgets.QPushButton('Plot', self)
        self.browser = QtWebEngineWidgets.QWebEngineView(self)

        vlayout = QtWidgets.QVBoxLayout(self)
        vlayout.addWidget(self.button, alignment=QtCore.Qt.AlignHCenter)
        vlayout.addWidget(self.browser)

        self.button.clicked.connect(self.show_graph)
        self.resize(1000,800)

    def show_graph(self):
        df = px.data.tips()
        fig = px.box(df, x="day", y="total_bill", color="smoker")
        fig.update_traces(quartilemethod="exclusive") # or "inclusive", or "linear" by default
        self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))
I have a csv file with data about crypto such as timestamp, open, high, low, close, volume and I wanna display a CandleStick.
I modified the code keeping same structure as the one above and everytime I click the button, my application is closing and I receive this error: Process finished with exit code -1073740791 (0xC0000409)

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import plotly.graph_objects as go
import pandas as pd

class CandlestickTab(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.button = QtWidgets.QPushButton('Show Candlestick Chart', self)
        self.browser = QtWebEngineWidgets.QWebEngineView(self)

        vlayout = QtWidgets.QVBoxLayout(self)
        vlayout.addWidget(self.button, alignment=QtCore.Qt.AlignHCenter)
        vlayout.addWidget(self.browser)

        self.button.clicked.connect(self.show_candlestick_chart)
        self.resize(1000, 800)

    def show_candlestick_chart(self):
        df = pd.read_csv('crypto.csv')
        if not df.empty:
            fig = go.Figure(data=[go.Candlestick(x=df['timestamp'],
                                                  open=df['open'],
                                                  high=df['high'],
                                                  low=df['low'],
                                                  close=df['close'])])
            self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))
        else:
            self.browser.setHtml("<p>No data available for plotting.</p>")
This is the main:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget
from home import HomeTab
from candlestick import CandlestickTab
from analiza_tehnica import AnalizaTehnicaTab
from sentiment_analysis import SentimentAnalysisTab
from alpha_get_data import AlphaGetData
# from news import NewsTab


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

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('Aplicația Mea cu Tab-uri')
        self.setGeometry(100, 100, 800, 600)
        tabs = QTabWidget()

        tabs.addTab(HomeTab(),"Home")

        tabs.addTab(AnalizaTehnicaTab(), "Analiza Tehnica")
        tabs.addTab(CandlestickTab(),"CandleStick")
        tabs.addTab(SentimentAnalysisTab(), "Sentiment Analysis")

        self.setCentralWidget(tabs)




if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainApp()
    window.show()
    sys.exit(app.exec_())
    app.setQuitOnLastWindowClosed(False)
Can someone help me with this, please?
Reply
#2
Process finished with exit code -1073740791 (0xC0000409) means "Program crashed, here is an error code to help you understand why." Didn't you get any kind of error trace? If so, please post.

Divide and conquer. First verify that you can generate html that you can view in a browser.
import plotly.graph_objects as go
import pandas as pd

df = pd.read_csv('crypto.csv')
fig = go.Figure(data=[go.Candlestick(
    x=df['timestamp'],
    open=df['open'],
    high=df['high'],
    low=df['low'],
    close=df['close'])])
fig.write_html("candlestick.html")
If opening "canclestick.html" in chrome or whatever displays the expected plot, the problem is in the Qt world. If not, there is something going on with how you are using plotly.
Reply
#3
If I create a new project and run your code, it works normally. It returns 0 and creates a html file in the folder which I can open and visualise.
In my project, If I try replacing this line
self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))
with this
fig.write_html("candlestick.html")
My app crashed with same error.

I tried adding a trace like this :
def show_candlestick_chart(self):
    print("show_candlestick_chart: Entering function")  # Print to indicate function start
    if self.df is not None and not self.df.empty:
        print("show_candlestick_chart: Generating Candlestick Chart")  # Print before generating chart
        try:
            fig = go.Figure(data=[go.Candlestick(x=self.df['timestamp'],
                                                  open=self.df['open'],
                                                  high=self.df['high'],
                                                  low=self.df['low'],
                                                  close=self.df['close'])])
            print("show_candlestick_chart: Chart generated successfully")  # Print if chart generated
            try:
                html_content = fig.to_html(include_plotlyjs='cdn')
                print("show_candlestick_chart: HTML content generated")  # Print if HTML content generated
                try:
                    self.browser.setHtml(html_content)
                    print("show_candlestick_chart: HTML content set in browser")  # Print if content set in browser
                except Exception as set_html_exception:
                    print("show_candlestick_chart: Error setting HTML content in browser:", set_html_exception)
            except Exception as html_exception:
                print("show_candlestick_chart: Error generating HTML content:", html_exception)
        except Exception as chart_exception:
            print("show_candlestick_chart: Error generating chart:", chart_exception)
    else:
        print("show_candlestick_chart: No data to plot")  # Print if no data
        self.browser.setHtml("<p>No data available for plotting.</p>")
    print("show_candlestick_chart: Exiting function")  # Print to indicate function end
But it's not helpful because my application is crashing as soon as I am clicking on the specific tab and I get no trace.
I am not sure if I should move to Tkinter or not because I dont know if there is a issue with my system or not
Reply
#4
So the crash is as soon as you open the tab? Not when you try to plot?

Step 2 of Divide and Conquer. Try running outside the context of the main application.
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import plotly.graph_objects as go
import pandas as pd
 
class CandlestickTab(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.button = QtWidgets.QPushButton('Show Candlestick Chart', self)
        self.browser = QtWebEngineWidgets.QWebEngineView(self)
 
        vlayout = QtWidgets.QVBoxLayout(self)
        vlayout.addWidget(self.button, alignment=QtCore.Qt.AlignHCenter)
        vlayout.addWidget(self.browser)
 
        self.button.clicked.connect(self.show_candlestick_chart)
        self.resize(1000, 800)
 
    def show_candlestick_chart(self):
        df = pd.read_csv('crypto.csv')
        if not df.empty:
            fig = go.Figure(data=[go.Candlestick(x=df['timestamp'],
                                                  open=df['open'],
                                                  high=df['high'],
                                                  low=df['low'],
                                                  close=df['close'])])
            self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))
        else:
            self.browser.setHtml("<p>No data available for plotting.</p>")

app = QtWidgets.QApplication(sys.argv)
window = CandlestickTab()
window.show()
sys.exit(app.exec_())
Reply
#5
I actually solved it.
The problem has on the csv import, a column had a different name.
Thanks so much for your help!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Interaction between Matplotlib window, Python prompt and TKinter window NorbertMoussy 3 540 Mar-17-2024, 09:37 AM
Last Post: deanhystad
Exclamation [Tkinter] Error when closing the main window with destroy TomasSanchexx 1 794 Aug-06-2023, 01:54 AM
Last Post: deanhystad
Question closing a "nested" window with a button in PySimpleGUI and repeating this process Robby_PY 9 13,638 Jan-18-2021, 10:21 PM
Last Post: Serafim
  [PyQt] Received RunTimeError after script concludes, closing Dialog Window (clicking x-out) skipper0802 0 2,577 Oct-09-2020, 09:23 PM
Last Post: skipper0802
  How to display results from terminal window onto tkinter. buttercup 0 3,660 Jul-21-2020, 04:41 AM
Last Post: buttercup
  Closing window on button click not working kenwatts275 4 3,811 May-03-2020, 01:59 PM
Last Post: deanhystad
  tkinter window and turtle window error 1885 3 6,752 Nov-02-2019, 12:18 PM
Last Post: 1885
  [split] Closing a window but not the whole program scriptdrache 1 2,339 Jun-25-2019, 03:43 PM
Last Post: joe_momma
  Huge code problems (buttons(PyQt5),PyQt5 Threads, Windows etc) ZenWoR 0 2,841 Apr-06-2019, 11:15 PM
Last Post: ZenWoR
  [Pyqt5]Display name of new inserted USB stick on GUI Atalanttore 0 3,011 Mar-24-2019, 08:29 PM
Last Post: Atalanttore

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020