上面的代码会使我的窗口关闭
时间: 2024-03-06 07:49:56 浏览: 20
如果您的窗口在执行上面的代码后关闭了,可能是因为在关闭窗口时没有正确地处理事件循环。在 PyQt 中,当您关闭一个窗口时,会触发`QCloseEvent`事件,您需要在事件处理方法中正确地关闭窗口并停止事件循环。下面是一个示例代码:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout
from PyQt5.QtGui import QPixmap
import sys
import time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.label = QLabel()
self.button = QPushButton('更新图片')
self.button.clicked.connect(self.on_click)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
def on_click(self):
self.print_window('检测完毕')
# 先将 QLabel 中的 pixmap 置空
self.label.setPixmap(None)
newname = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
main(newname)
pixmap = QPixmap('%s.png' % newname)
self.label.setPixmap(pixmap)
self.label.setScaledContents(True) # 图片适应 label 的大小
def print_window(self, msg):
print(msg)
def closeEvent(self, event):
# 停止事件循环
QApplication.quit()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
# 启动事件循环
sys.exit(app.exec_())
```
在这个示例中,我们重写了`MainWindow`的`closeEvent`方法,当窗口关闭时,会触发`QCloseEvent`事件并调用`closeEvent`方法。在该方法中,我们调用`QApplication.quit`方法停止事件循环,从而正确关闭窗口。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)