PyQt:按下按钮时没有显示第二个窗口
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PyQt:按下按钮时没有显示第二个窗口相关的知识,希望对你有一定的参考价值。
尝试制作我的第一个PyQt5应用程序,当我单击我的按钮时,代码运行但我的选项窗口没有出现在屏幕上。
#!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication, QLabel, QPushButton, QVBoxLayout
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import QSize
class MainWindow(QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.initUI()
def initUI(self):
self.setWindowTitle('Main Window')
label = QLabel(self)
pixmap = QPixmap('background.png')
label.setPixmap(pixmap)
self.resize(pixmap.width(), pixmap.height())
self.initButtons()
self.center()
self.show()
def initButtons(self):
self.button = QPushButton('', self)
# button style things...
self.button.clicked.connect(self.handleButton)
self.dialog = OptionsWindow(self)
def handleButton(self):
self.dialog.show()
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
class OptionsWindow(QWidget):
def __init__(self, parent=None):
super(OptionsWindow, self).__init__(parent)
self.setWindowTitle("Options")
self.resize(200,200)
self.center()
self.show()
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def main():
app = QApplication(sys.argv)
main = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
我错过了什么吗?我尝试了各种各样的东西,比如删除“中心”功能,删除背景图像等,但按下按钮时仍然没有第二个窗口
答案
试试吧:
import sys
from PyQt5.QtWidgets import (QWidget, QDesktopWidget, QApplication,
QLabel, QPushButton, QVBoxLayout)
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import QSize
class MainWindow(QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.initUI()
def initUI(self):
self.setWindowTitle('Main Window')
label = QLabel(self)
pixmap = QPixmap('D:/_Qt/img/pyqt.jpg')
label.setPixmap(pixmap)
self.resize(pixmap.width(), pixmap.height())
self.initButtons()
self.center()
self.show()
def initButtons(self):
self.button = QPushButton('button', self)
# button style things...
self.button.clicked.connect(self.handleButton)
# self.dialog = OptionsWindow(self) # ---
def handleButton(self):
self.dialog = OptionsWindow() # +++ - self
self.dialog.show()
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
class OptionsWindow(QWidget):
def __init__(self, parent=None):
super(OptionsWindow, self).__init__(parent)
self.setWindowTitle("Options")
self.resize(200,200)
self.center()
# self.show()
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def main():
app = QApplication(sys.argv)
main = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
以上是关于PyQt:按下按钮时没有显示第二个窗口的主要内容,如果未能解决你的问题,请参考以下文章