PyQt5:如何从系统任务栏图标上下文菜单启动窗口?

时间:2018-11-24 16:26:08

标签: python python-3.x pyqt5 qmainwindow qsystemtrayicon

我有两个单独的文件,一个创建系统任务栏图标和上下文菜单,另一个创建用于接受用户输入的窗口。

traywindow.py包含以下内容:

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()

哪个会产生:

enter image description here

trayapp.py包含以下内容:

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)

哪个会产生:

Window

我想从上下文菜单中启动该窗口,因此当我单击Preferences...时,它将打开Set Account窗口,当我填写该字段并单击OK时,将其捕获到变量中/将其作为参数传递到trayapp.py文件中。当前,当我点击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]

我是PyQt5的新手,感觉自己缺少一些基本知识。从错误的角度来看,我认为这与最后调用每个文件以生成其UI的方式有关,但是到目前为止,我在文档中都没有找到答案。

1 个答案:

答案 0 :(得分:1)

您只能拥有一个QApplication,并在displayWindow中创建第二个QApplication,而是创建一个MainWindow并且不调用displayWindow。

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