不起作用的代码是这样的:(只需考虑注释部分;Main() 仅用于创建 systrayicon(由于 tkinter,它最初是用 win32gui 实现的,但在 qt 中它的代码要少得多。我知道混合这些工具包/框架是不好的)。
from tkinter import Tk,Menu,TOP,Frame,X,NO,BOTH,YES,BOTTOM
from PyQt4.QtGui import *
import sys
class Note():
def __init__(self):
self.root=Tk()
print("Note has been created, but is not being displayed. Why? \n If Exit is clicked, it shows.")
class Main():
def __init__(self):
self.notes=[]
self.app = QApplication(sys.argv)
self.app.setQuitOnLastWindowClosed(False);
self.trayIcon = QSystemTrayIcon(QIcon("J:\\python\\SimpleNotes.ico"), self.app)
self.menu = QMenu()
self.newWindow = self.menu.addAction("new Note")
self.separator = self.menu.addSeparator()
self.exitAction = self.menu.addAction("Exit")
self.exitAction.triggered.connect(self.close)
self.newWindow.triggered.connect(self.newNote)
self.trayIcon.setContextMenu(self.menu)
self.trayIcon.show()
self.app.exec()
def newNote(self):
print("Create new note entry has been clicked")
note=Note()
#note.show() #because note is of Tk, it gots no show()
self.notes.append(note)
def close(self):
self.trayIcon.hide()
self.app.exit()
print("Exit menu entry has been clicked")
Main()
有效的代码是这样的:(我只替换了 Note() 部分,现在用 Qt 而不是 tkinter,并让注释显示 Qt 的原因)
import sys
from PyQt4.QtGui import *
class Note(QMainWindow):
def __init__(self):
super(Note,self).__init__()
self.w=QWidget()
self.setWindowTitle("Note")
self.setCentralWidget(self.w)
class Main():
def __init__(self):
self.notes=[]
self.app = QApplication(sys.argv)
self.app.setQuitOnLastWindowClosed(False);
self.trayIcon = QSystemTrayIcon(QIcon("J:\\python\\SimpleNotes.ico"), self.app)
self.menu = QMenu()
self.newWindow = self.menu.addAction("new Note")
self.separator = self.menu.addSeparator()
self.exitAction = self.menu.addAction("Exit")
self.exitAction.triggered.connect(self.close)
self.newWindow.triggered.connect(self.newNote)
self.trayIcon.setContextMenu(self.menu)
self.trayIcon.show()
self.app.exec()
def newNote(self):
print("Create new note entry has been clicked")
note=Note()
note.show()
self.notes.append(note)
def close(self):
self.trayIcon.hide()
self.app.exit()
print("Exit menu entry has been clicked")
Main()