In this PyQt6 article we want to learn How to Open Second Window in PyQt6, so PyQt6 is popular Python binding for Qt toolkit. it allows developers to create graphical user interfaces for their Python applications.
So first of all you need to install PyQt6 and you can use pip for that.
1 |
pip install PyQt6 |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel from PyQt6.QtGui import QFont class MainWindow(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Main Window") self.second_window = None button = QPushButton("Open Second Window") button.clicked.connect(self.open_second_window) layout = QVBoxLayout() layout.addWidget(button) self.setLayout(layout) def open_second_window(self): if self.second_window is None: self.second_window = SecondWindow() self.second_window.show() class SecondWindow(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Second Window") label = QLabel("Second Window - geekscoders.com") label.setFont(QFont("Times", 15)) label.setStyleSheet('color:red') layout = QVBoxLayout() layout.addWidget(label) self.setLayout(layout) if __name__ == "__main__": app = QApplication([]) window = MainWindow() window.show() app.exec() |
In the above e code we have create a second_window attribute on the MainWindow class and initialize it to None. when open_second_window method is called, it checks if the second_window attribute is None. if it is None, it creates a new SecondWindow object and assigns it to the second_window attribute. if the second_window attribute is not None, it simply shows the existing SecondWindow object.
this should keep the SecondWindow object alive even after the open_second_window method finishes executing, and it allows the window to remain open.
Run the complete code and this will be the result

Learn More on Python GUI
- How to Create Label in PySide6
- How to Create Button in Python & PySide6
- How to Use Qt Designer with PySide6
- How to Add Icon to PySide6 Window
- How to Load UI in Python PySide6
- How to Create RadioButton in PySide6
- How to Create ComboBox in PySide6
- How to Create CheckBox in Python PySide6
- Responsive Applications with PyQt6 Multithreading
- Event Handling in Python and PyQt6
- How to Use Stylesheets in Python PyQt6
- How to Open Second Window in PyQt5