Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Python : When trying to plot a second figure, an empty tkinter window is displayed
QtWS25 Last Chance

Python : When trying to plot a second figure, an empty tkinter window is displayed

Scheduled Pinned Locked Moved Solved General and Desktop
13 Posts 2 Posters 6.1k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • ? Offline
    ? Offline
    A Former User
    wrote on 15 May 2017, 14:09 last edited by
    #1

    -2
    down vote
    favorite
    I have an interface with 4 tabs, in each tab, I have a button which when clicked generates a graph with matplotlib. We can display multiple plots on the same graph.

    Before, I have several problems such the graph window is frozen or cannot display multiple plots and I resolved it by this code :

     fig = plt.figure(self.numFiguresPlot2_1) 
     fig.canvas.set_window_title(self.DropDownListDisplaySector2_1.currentText())
     
     x = np.arange(0, self.stockParam.nTotZones, 1)
     y = pd.to_numeric(matrix4["Price"])
     print("Moyenne = ")
     print(y.mean(0))
     z = pd.to_numeric(matrix4["Adjust"]*y)/100 + y
      # plot data
     if(firstPlot):
             price = plt.plot(x, y, label = ("Price"))
             shadowPrice = plt.plot(x, z, label = ("Price + adjust for iteration "+self.DropDownListDisplayIter2_1.currentText()))
     
    plt.ion()
    plt.legend() 
    draw_thread = threading.Thread(target=plt.show)  
    draw_thread.start()
    plt.ioff()
    

    Now I have another problem. In fact, when I close the first figure and I try to plot a second figure, an empty tkinter window is displayed and the program crashes. I don't understand this problem.

    Can you help me ?

    Thanks in advance.

    1 Reply Last reply
    0
    • ? Offline
      ? Offline
      A Former User
      wrote on 15 May 2017, 15:03 last edited by
      #2

      Hello,

      I have another problem. When trying to integrate my code as a pluging in QGIS, I get this error :

      Exception in thread Thread-1:
      Traceback (most recent call last):
      File "C:\OSGEO4~1\apps\Python27\lib\threading.py", line 808, in __bootstrap_inner
      self.run()
      File "C:\OSGEO4~1\apps\Python27\lib\threading.py", line 761, in run
      self.__target(*self.__args, **self.__kwargs)
      File "C:\OSGEO4~1\apps\Python27\lib\site-packages\matplotlib\pyplot.py", line 253, in show
      return _show(*args, **kw)
      File "C:\OSGEO4~1\apps\Python27\lib\site-packages\matplotlib\backend_bases.py", line 193, in call
      self.mainloop()
      File "C:\OSGEO4~1\apps\Python27\lib\site-packages\matplotlib\backends\backend_qt5.py", line 150, in mainloop
      signal.signal(signal.SIGINT, signal.SIG_DFL)
      ValueError: signal only works in main thread

      J 1 Reply Last reply 16 May 2017, 04:37
      0
      • ? A Former User
        15 May 2017, 15:03

        Hello,

        I have another problem. When trying to integrate my code as a pluging in QGIS, I get this error :

        Exception in thread Thread-1:
        Traceback (most recent call last):
        File "C:\OSGEO4~1\apps\Python27\lib\threading.py", line 808, in __bootstrap_inner
        self.run()
        File "C:\OSGEO4~1\apps\Python27\lib\threading.py", line 761, in run
        self.__target(*self.__args, **self.__kwargs)
        File "C:\OSGEO4~1\apps\Python27\lib\site-packages\matplotlib\pyplot.py", line 253, in show
        return _show(*args, **kw)
        File "C:\OSGEO4~1\apps\Python27\lib\site-packages\matplotlib\backend_bases.py", line 193, in call
        self.mainloop()
        File "C:\OSGEO4~1\apps\Python27\lib\site-packages\matplotlib\backends\backend_qt5.py", line 150, in mainloop
        signal.signal(signal.SIGINT, signal.SIG_DFL)
        ValueError: signal only works in main thread

        J Offline
        J Offline
        jsulm
        Lifetime Qt Champion
        wrote on 16 May 2017, 04:37 last edited by jsulm
        #3

        @EJWA said in Python : When trying to plot a second figure, an empty tkinter window is displayed:

        ValueError: signal only works in main thread

        This error message actually tells you what is wrong: signal() can only be used in main thread. You can find this information in Python documentation: https://docs.python.org/2/library/signal.html
        "Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution."

        https://forum.qt.io/topic/113070/qt-code-of-conduct

        ? 1 Reply Last reply 16 May 2017, 06:56
        1
        • J jsulm
          16 May 2017, 04:37

          @EJWA said in Python : When trying to plot a second figure, an empty tkinter window is displayed:

          ValueError: signal only works in main thread

          This error message actually tells you what is wrong: signal() can only be used in main thread. You can find this information in Python documentation: https://docs.python.org/2/library/signal.html
          "Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution."

          ? Offline
          ? Offline
          A Former User
          wrote on 16 May 2017, 06:56 last edited by
          #4

          Hello @jsulm and thanks for your reply.

          I have never used signals and I have no idea how to use it in my case. Could you give me some examples ?

          Thanks in advance.

          J 1 Reply Last reply 16 May 2017, 07:06
          0
          • ? A Former User
            16 May 2017, 06:56

            Hello @jsulm and thanks for your reply.

            I have never used signals and I have no idea how to use it in my case. Could you give me some examples ?

            Thanks in advance.

            J Offline
            J Offline
            jsulm
            Lifetime Qt Champion
            wrote on 16 May 2017, 07:06 last edited by
            #5

            @EJWA To clarify: it's not about Qt signals, its about UNIX signals. I don't know your code, so I don't know where this signal() Python stuff is used. What exactly are you integrating and how? And when does this error occur?
            Are you using any threads?
            "File "C:\OSGEO4~1\apps\Python27\lib\site-packages\matplotlib\backends\backend_qt5.py", line 150, in mainloop
            signal.signal(signal.SIGINT, signal.SIG_DFL)"
            C:\OSGEO4~1\apps\Python27\lib\site-packages\matplotlib\backends\backend_qt5.py - is this what you're integrating? Its the file where the error occurs.

            https://forum.qt.io/topic/113070/qt-code-of-conduct

            1 Reply Last reply
            0
            • ? Offline
              ? Offline
              A Former User
              wrote on 16 May 2017, 07:20 last edited by
              #6

              Hello,

              I am integrating my code as a plugin in QGIS using this method http://www.qgistutorials.com/fr/docs/building_a_python_plugin.html.

              It consists on GUI interface which have a button when clicked generate graphs with matplotlib. Every time, we select an iteration in GUI, a plot will be drawn on the graph. So, the graph can have many plots.

              Before, I have a problem with graph windows : I can't control it : I can't close it or save or zoom, so I use threading which helps me. Here is what I put in my code (function used when the button "generate graph" is clicked) :

              fig = plt.figure(self.numFiguresPlot2_1) 
               fig.canvas.set_window_title(self.DropDownListDisplaySector2_1.currentText())
               
               x = np.arange(0, self.stockParam.nTotZones, 1)
               y = pd.to_numeric(matrix4["Price"])
               print("Moyenne = ")
               print(y.mean(0))
               z = pd.to_numeric(matrix4["Adjust"]*y)/100 + y
                # plot data
               if(firstPlot):
                       price = plt.plot(x, y, label = ("Price"))
                       shadowPrice = plt.plot(x, z, label = ("Price + adjust for iteration "+self.DropDownListDisplayIter2_1.currentText()))
               
              plt.ion()
              plt.legend() 
              draw_thread = threading.Thread(target=plt.show)  
              draw_thread.start()
              plt.ioff()
              
              J 1 Reply Last reply 16 May 2017, 07:24
              0
              • ? A Former User
                16 May 2017, 07:20

                Hello,

                I am integrating my code as a plugin in QGIS using this method http://www.qgistutorials.com/fr/docs/building_a_python_plugin.html.

                It consists on GUI interface which have a button when clicked generate graphs with matplotlib. Every time, we select an iteration in GUI, a plot will be drawn on the graph. So, the graph can have many plots.

                Before, I have a problem with graph windows : I can't control it : I can't close it or save or zoom, so I use threading which helps me. Here is what I put in my code (function used when the button "generate graph" is clicked) :

                fig = plt.figure(self.numFiguresPlot2_1) 
                 fig.canvas.set_window_title(self.DropDownListDisplaySector2_1.currentText())
                 
                 x = np.arange(0, self.stockParam.nTotZones, 1)
                 y = pd.to_numeric(matrix4["Price"])
                 print("Moyenne = ")
                 print(y.mean(0))
                 z = pd.to_numeric(matrix4["Adjust"]*y)/100 + y
                  # plot data
                 if(firstPlot):
                         price = plt.plot(x, y, label = ("Price"))
                         shadowPrice = plt.plot(x, z, label = ("Price + adjust for iteration "+self.DropDownListDisplayIter2_1.currentText()))
                 
                plt.ion()
                plt.legend() 
                draw_thread = threading.Thread(target=plt.show)  
                draw_thread.start()
                plt.ioff()
                
                J Offline
                J Offline
                jsulm
                Lifetime Qt Champion
                wrote on 16 May 2017, 07:24 last edited by
                #7

                @EJWA In Qt you should never do any UI related stuff in other thread than GUI thread! This is not supported.

                https://forum.qt.io/topic/113070/qt-code-of-conduct

                ? 1 Reply Last reply 16 May 2017, 07:49
                0
                • J jsulm
                  16 May 2017, 07:24

                  @EJWA In Qt you should never do any UI related stuff in other thread than GUI thread! This is not supported.

                  ? Offline
                  ? Offline
                  A Former User
                  wrote on 16 May 2017, 07:49 last edited by
                  #8

                  @jsulm So any alternatives to do that ? I have used other solutions like subprocess http://stackoverflow.com/questions/36675269/cannot-move-matplotlib-plot-window-and-exit-it-using-red-x-button and I don't get the result what I want. I am really confused to do that.

                  J 1 Reply Last reply 16 May 2017, 07:51
                  0
                  • ? A Former User
                    16 May 2017, 07:49

                    @jsulm So any alternatives to do that ? I have used other solutions like subprocess http://stackoverflow.com/questions/36675269/cannot-move-matplotlib-plot-window-and-exit-it-using-red-x-button and I don't get the result what I want. I am really confused to do that.

                    J Offline
                    J Offline
                    jsulm
                    Lifetime Qt Champion
                    wrote on 16 May 2017, 07:51 last edited by
                    #9

                    @EJWA "Before, I have a problem with graph windows : I can't control it : I can't close it or save or zoom" - you should investigate why. It should work without threads.

                    https://forum.qt.io/topic/113070/qt-code-of-conduct

                    ? 1 Reply Last reply 16 May 2017, 08:01
                    0
                    • J jsulm
                      16 May 2017, 07:51

                      @EJWA "Before, I have a problem with graph windows : I can't control it : I can't close it or save or zoom" - you should investigate why. It should work without threads.

                      ? Offline
                      ? Offline
                      A Former User
                      wrote on 16 May 2017, 08:01 last edited by
                      #10

                      @jsulm When I investigate I found this answer ( http://stackoverflow.com/questions/36675269/cannot-move-matplotlib-plot-window-and-exit-it-using-red-x-button)

                      "his is because your matplotlib figure and your PyQt GUI are both running in the same main thread. Since they are in the main thread, only one of them has the CPU for itself"

                      If it is not correct, I must search for another reason.

                      J 1 Reply Last reply 16 May 2017, 08:05
                      0
                      • ? A Former User
                        16 May 2017, 08:01

                        @jsulm When I investigate I found this answer ( http://stackoverflow.com/questions/36675269/cannot-move-matplotlib-plot-window-and-exit-it-using-red-x-button)

                        "his is because your matplotlib figure and your PyQt GUI are both running in the same main thread. Since they are in the main thread, only one of them has the CPU for itself"

                        If it is not correct, I must search for another reason.

                        J Offline
                        J Offline
                        jsulm
                        Lifetime Qt Champion
                        wrote on 16 May 2017, 08:05 last edited by
                        #11

                        @EJWA In the link you posted there is a workaround:

                        import subprocess
                        ...
                        
                            # When you click the button in your PyQT GUI,
                            # Create a new process:
                            myMatProcess = subprocess.Popen(['python', 'myGraph.py'], shell=True)
                        

                        https://forum.qt.io/topic/113070/qt-code-of-conduct

                        1 Reply Last reply
                        0
                        • ? Offline
                          ? Offline
                          A Former User
                          wrote on 16 May 2017, 08:23 last edited by
                          #12

                          Hello,

                          Finally, I found the solution .

                          First, in my script I put :

                          import matplotlib
                          matplotlib.use('Qt4Agg')

                          then in function of plot I put :

                          plt.legend()
                          plt.show()
                          plt.draw()

                          and it works for me correctly except there is a warning :

                          QCoreApplication::exec: The event loop is already running

                          1 Reply Last reply
                          0
                          • ? Offline
                            ? Offline
                            A Former User
                            wrote on 16 May 2017, 08:43 last edited by
                            #13

                            import matplotlib
                            matplotlib.use('Qt4Agg')

                            plt.legend()
                            plt.draw()
                            plt.show(block=False)

                            1 Reply Last reply
                            0

                            3/13

                            16 May 2017, 04:37

                            topic:navigator.unread, 10
                            • Login

                            • Login or register to search.
                            3 out of 13
                            • First post
                              3/13
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • Users
                            • Groups
                            • Search
                            • Get Qt Extensions
                            • Unsolved