PyQt5: how do I launch a window from a system tray icon context menu?












0















I have two separate files, one that creates a system tray icon and context menu, and another a window to take user input.



traywindow.py contains this:



import sys
import os
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize

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

self.setMinimumSize(QSize(320, 172))
self.setWindowTitle("Set Account")

# Setup username field
self.username_label = QLabel(self)
self.username_label.setText('Username')
self.username_field = QLineEdit(self)
self.username_label.move(45, 20)
self.username_field.move(115, 23)
self.username_field.resize(150, 25)

# Setup OK button
pybutton = QPushButton('OK', self)
pybutton.clicked.connect(self.buttonClicked)
pybutton.resize(100,32)
pybutton.move(110, 128)

def buttonClicked(self):
print('Username: ' + self.username_field.text())

def displayWindow():
app = QtWidgets.QApplication(sys.argv)
preferences_window = MainWindow()
preferences_window.show()
sys.exit(app.exec_())

if __name__ == "__main__":
displayWindow()


Which produces:



enter image description here



trayapp.py contains this:



import os
import sys
import traywindow
from PyQt5 import QtWidgets, QtCore, QtGui

class SystemTrayIcon(QtWidgets.QSystemTrayIcon):

def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)

menu = QtWidgets.QMenu(parent)
prefs_action = menu.addAction('Preferences...')
self.setContextMenu(menu)
prefs_action.triggered.connect(self.setPrefs)

def setPrefs(self):
traywindow.displayWindow()

def main(image):
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
trayIcon.show()
sys.exit(app.exec_())

if __name__ == '__main__':
icon = 'icon.png'
main(icon)


Which produces:



Window



I want to launch the window from my context menu, so when I click on Preferences... it will open the Set Account window, and when I fill in the field and click on OK, capture that into variables/pass those along as arguments in the trayapp.py file. Currently, my attempt in the code above gives me this when I click on Preferences...:



Traceback (most recent call last):
File "/Users/Username/Downloads/trayapp.py", line 17, in setPrefs
traywindow.displayWindow()
File "/Users/Username/Downloads/traywindow.py", line 36, in displayWindow
sys.exit(app.exec_())
SystemExit: -1
[Finished in 3.0s with exit code -6]


I'm new to PyQt5 and feel like I'm missing something fundamental. From the error I think it's to do with how each file is called at the end to produce its UI, but I haven't found an answer in the docs so far.










share|improve this question



























    0















    I have two separate files, one that creates a system tray icon and context menu, and another a window to take user input.



    traywindow.py contains this:



    import sys
    import os
    from PyQt5 import QtCore, QtWidgets
    from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
    from PyQt5.QtWidgets import QPushButton
    from PyQt5.QtCore import QSize

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

    self.setMinimumSize(QSize(320, 172))
    self.setWindowTitle("Set Account")

    # Setup username field
    self.username_label = QLabel(self)
    self.username_label.setText('Username')
    self.username_field = QLineEdit(self)
    self.username_label.move(45, 20)
    self.username_field.move(115, 23)
    self.username_field.resize(150, 25)

    # Setup OK button
    pybutton = QPushButton('OK', self)
    pybutton.clicked.connect(self.buttonClicked)
    pybutton.resize(100,32)
    pybutton.move(110, 128)

    def buttonClicked(self):
    print('Username: ' + self.username_field.text())

    def displayWindow():
    app = QtWidgets.QApplication(sys.argv)
    preferences_window = MainWindow()
    preferences_window.show()
    sys.exit(app.exec_())

    if __name__ == "__main__":
    displayWindow()


    Which produces:



    enter image description here



    trayapp.py contains this:



    import os
    import sys
    import traywindow
    from PyQt5 import QtWidgets, QtCore, QtGui

    class SystemTrayIcon(QtWidgets.QSystemTrayIcon):

    def __init__(self, icon, parent=None):
    QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)

    menu = QtWidgets.QMenu(parent)
    prefs_action = menu.addAction('Preferences...')
    self.setContextMenu(menu)
    prefs_action.triggered.connect(self.setPrefs)

    def setPrefs(self):
    traywindow.displayWindow()

    def main(image):
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QWidget()
    trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
    trayIcon.show()
    sys.exit(app.exec_())

    if __name__ == '__main__':
    icon = 'icon.png'
    main(icon)


    Which produces:



    Window



    I want to launch the window from my context menu, so when I click on Preferences... it will open the Set Account window, and when I fill in the field and click on OK, capture that into variables/pass those along as arguments in the trayapp.py file. Currently, my attempt in the code above gives me this when I click on Preferences...:



    Traceback (most recent call last):
    File "/Users/Username/Downloads/trayapp.py", line 17, in setPrefs
    traywindow.displayWindow()
    File "/Users/Username/Downloads/traywindow.py", line 36, in displayWindow
    sys.exit(app.exec_())
    SystemExit: -1
    [Finished in 3.0s with exit code -6]


    I'm new to PyQt5 and feel like I'm missing something fundamental. From the error I think it's to do with how each file is called at the end to produce its UI, but I haven't found an answer in the docs so far.










    share|improve this question

























      0












      0








      0








      I have two separate files, one that creates a system tray icon and context menu, and another a window to take user input.



      traywindow.py contains this:



      import sys
      import os
      from PyQt5 import QtCore, QtWidgets
      from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
      from PyQt5.QtWidgets import QPushButton
      from PyQt5.QtCore import QSize

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

      self.setMinimumSize(QSize(320, 172))
      self.setWindowTitle("Set Account")

      # Setup username field
      self.username_label = QLabel(self)
      self.username_label.setText('Username')
      self.username_field = QLineEdit(self)
      self.username_label.move(45, 20)
      self.username_field.move(115, 23)
      self.username_field.resize(150, 25)

      # Setup OK button
      pybutton = QPushButton('OK', self)
      pybutton.clicked.connect(self.buttonClicked)
      pybutton.resize(100,32)
      pybutton.move(110, 128)

      def buttonClicked(self):
      print('Username: ' + self.username_field.text())

      def displayWindow():
      app = QtWidgets.QApplication(sys.argv)
      preferences_window = MainWindow()
      preferences_window.show()
      sys.exit(app.exec_())

      if __name__ == "__main__":
      displayWindow()


      Which produces:



      enter image description here



      trayapp.py contains this:



      import os
      import sys
      import traywindow
      from PyQt5 import QtWidgets, QtCore, QtGui

      class SystemTrayIcon(QtWidgets.QSystemTrayIcon):

      def __init__(self, icon, parent=None):
      QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)

      menu = QtWidgets.QMenu(parent)
      prefs_action = menu.addAction('Preferences...')
      self.setContextMenu(menu)
      prefs_action.triggered.connect(self.setPrefs)

      def setPrefs(self):
      traywindow.displayWindow()

      def main(image):
      app = QtWidgets.QApplication(sys.argv)
      w = QtWidgets.QWidget()
      trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
      trayIcon.show()
      sys.exit(app.exec_())

      if __name__ == '__main__':
      icon = 'icon.png'
      main(icon)


      Which produces:



      Window



      I want to launch the window from my context menu, so when I click on Preferences... it will open the Set Account window, and when I fill in the field and click on OK, capture that into variables/pass those along as arguments in the trayapp.py file. Currently, my attempt in the code above gives me this when I click on Preferences...:



      Traceback (most recent call last):
      File "/Users/Username/Downloads/trayapp.py", line 17, in setPrefs
      traywindow.displayWindow()
      File "/Users/Username/Downloads/traywindow.py", line 36, in displayWindow
      sys.exit(app.exec_())
      SystemExit: -1
      [Finished in 3.0s with exit code -6]


      I'm new to PyQt5 and feel like I'm missing something fundamental. From the error I think it's to do with how each file is called at the end to produce its UI, but I haven't found an answer in the docs so far.










      share|improve this question














      I have two separate files, one that creates a system tray icon and context menu, and another a window to take user input.



      traywindow.py contains this:



      import sys
      import os
      from PyQt5 import QtCore, QtWidgets
      from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
      from PyQt5.QtWidgets import QPushButton
      from PyQt5.QtCore import QSize

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

      self.setMinimumSize(QSize(320, 172))
      self.setWindowTitle("Set Account")

      # Setup username field
      self.username_label = QLabel(self)
      self.username_label.setText('Username')
      self.username_field = QLineEdit(self)
      self.username_label.move(45, 20)
      self.username_field.move(115, 23)
      self.username_field.resize(150, 25)

      # Setup OK button
      pybutton = QPushButton('OK', self)
      pybutton.clicked.connect(self.buttonClicked)
      pybutton.resize(100,32)
      pybutton.move(110, 128)

      def buttonClicked(self):
      print('Username: ' + self.username_field.text())

      def displayWindow():
      app = QtWidgets.QApplication(sys.argv)
      preferences_window = MainWindow()
      preferences_window.show()
      sys.exit(app.exec_())

      if __name__ == "__main__":
      displayWindow()


      Which produces:



      enter image description here



      trayapp.py contains this:



      import os
      import sys
      import traywindow
      from PyQt5 import QtWidgets, QtCore, QtGui

      class SystemTrayIcon(QtWidgets.QSystemTrayIcon):

      def __init__(self, icon, parent=None):
      QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)

      menu = QtWidgets.QMenu(parent)
      prefs_action = menu.addAction('Preferences...')
      self.setContextMenu(menu)
      prefs_action.triggered.connect(self.setPrefs)

      def setPrefs(self):
      traywindow.displayWindow()

      def main(image):
      app = QtWidgets.QApplication(sys.argv)
      w = QtWidgets.QWidget()
      trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
      trayIcon.show()
      sys.exit(app.exec_())

      if __name__ == '__main__':
      icon = 'icon.png'
      main(icon)


      Which produces:



      Window



      I want to launch the window from my context menu, so when I click on Preferences... it will open the Set Account window, and when I fill in the field and click on OK, capture that into variables/pass those along as arguments in the trayapp.py file. Currently, my attempt in the code above gives me this when I click on Preferences...:



      Traceback (most recent call last):
      File "/Users/Username/Downloads/trayapp.py", line 17, in setPrefs
      traywindow.displayWindow()
      File "/Users/Username/Downloads/traywindow.py", line 36, in displayWindow
      sys.exit(app.exec_())
      SystemExit: -1
      [Finished in 3.0s with exit code -6]


      I'm new to PyQt5 and feel like I'm missing something fundamental. From the error I think it's to do with how each file is called at the end to produce its UI, but I haven't found an answer in the docs so far.







      python python-3.x pyqt5 qmainwindow qsystemtrayicon






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 16:26









      SidewinderSidewinder

      344




      344
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You can only have one QApplication and in displayWindow you are creating a second QApplication, instead create a MainWindow and do not call displayWindow.



          def setPrefs(self):
          self.window = traywindow.MainWindow()
          self.window.show()





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53460121%2fpyqt5-how-do-i-launch-a-window-from-a-system-tray-icon-context-menu%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You can only have one QApplication and in displayWindow you are creating a second QApplication, instead create a MainWindow and do not call displayWindow.



            def setPrefs(self):
            self.window = traywindow.MainWindow()
            self.window.show()





            share|improve this answer




























              1














              You can only have one QApplication and in displayWindow you are creating a second QApplication, instead create a MainWindow and do not call displayWindow.



              def setPrefs(self):
              self.window = traywindow.MainWindow()
              self.window.show()





              share|improve this answer


























                1












                1








                1







                You can only have one QApplication and in displayWindow you are creating a second QApplication, instead create a MainWindow and do not call displayWindow.



                def setPrefs(self):
                self.window = traywindow.MainWindow()
                self.window.show()





                share|improve this answer













                You can only have one QApplication and in displayWindow you are creating a second QApplication, instead create a MainWindow and do not call displayWindow.



                def setPrefs(self):
                self.window = traywindow.MainWindow()
                self.window.show()






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 25 '18 at 1:08









                eyllanesceyllanesc

                78.7k103256




                78.7k103256
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53460121%2fpyqt5-how-do-i-launch-a-window-from-a-system-tray-icon-context-menu%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Futebolista

                    Feedback on college project

                    Albești (Vaslui)