Skip to main content
 首页 » 编程设计

python之窗口不出现

2025年05月04日12jpfss

我写了一个程序,在系统托盘中创建一个图标,单击鼠标右键显示 3 点注释的上下文菜单,创建新注释和退出,按菜单创建新注释表单应该出现,但它没有出现。为什么?

from PyQt4 import QtCore, QtGui, uic 
import sys 
 
class NoteForm(QtGui.QDialog): 
    def __init__(self, parent=None): 
        QtGui.QDialog.__init__(self, parent) 
        uic.loadUi("note.ui", self) 
 
def main(): 
    app = QtGui.QApplication(sys.argv) 
 
    tray = QtGui.QSystemTrayIcon() 
    icon = app.style().standardIcon(QtGui.QStyle.SP_DesktopIcon) 
    tray.setIcon(icon) 
    tray.show() 
    CreateMenu(tray, app) 
    sys.exit(app.exec_()) 
 
def CreateMenu(tray, app): 
    m1 = QtGui.QMenu("Menu 1") 
    m2 = QtGui.QMenu("Notes", m1) 
    actNewNote=QtGui.QAction("Create new note", m1) 
    actNewNote.triggered.connect(viewNote) 
    #m1.addAction("Create new note", viewNote) 
    m1.addMenu(m2) 
    m1.addSeparator() 
    m1.addAction("Quit", app.quit) 
    tray.setContextMenu(m1) 
 
def viewNote(): 
    note=NoteForm() 
    note.show() 
 
 
if __name__ == '__main__': 
    main() 

注意.ui

<?xml version="1.0" encoding="UTF-8"?> 
<ui version="4.0"> 
 <class>WindowNote</class> 
 <widget class="QDialog" name="WindowNote"> 
  <property name="geometry"> 
   <rect> 
    <x>0</x> 
    <y>0</y> 
    <width>707</width> 
    <height>356</height> 
   </rect> 
  </property> 
  <property name="windowTitle"> 
   <string>Заметка</string> 
  </property> 
  <widget class="QWidget" name=""> 
   <property name="geometry"> 
    <rect> 
     <x>20</x> 
     <y>10</y> 
     <width>671</width> 
     <height>331</height> 
    </rect> 
   </property> 
   <layout class="QGridLayout" name="gridLayout"> 
    <item row="0" column="0" colspan="3"> 
     <widget class="QLineEdit" name="TitleNote"/> 
    </item> 
    <item row="1" column="0" colspan="3"> 
     <widget class="QTextEdit" name="textNote"/> 
    </item> 
    <item row="2" column="0"> 
     <widget class="QPushButton" name="buttonOK"> 
      <property name="text"> 
       <string>OK</string> 
      </property> 
     </widget> 
    </item> 
    <item row="2" column="1"> 
     <widget class="QPushButton" name="buttonCancel"> 
      <property name="text"> 
       <string>Отмена</string> 
      </property> 
     </widget> 
    </item> 
    <item row="2" column="2"> 
     <widget class="QPushButton" name="buttonDeleteNote"> 
      <property name="text"> 
       <string>Удалить заметку</string> 
      </property> 
     </widget> 
    </item> 
   </layout> 
  </widget> 
 </widget> 
 <resources/> 
 <connections/> 
</ui> 

请您参考如下方法:

viewNote 函数不会保存对它创建的 NoteForm 实例的引用。 show() 函数无阻塞地立即返回,因此对话框在显示后立即被垃圾回收。

要修复它,请使用 exec_运行对话框,或保留全局引用:

def viewNote(): 
    note = NoteForm() 
    note.exec_() 

或:

def viewNote(): 
    global note 
    note = NoteForm() 
    note.show()