Search code examples
pythonpyqtpyqt5

Window immediately closing


I faced the following problem: After clicking a button "Create" window opened for a millisecond and then closed.

main.py file:

from PyQt5.QtCore import Qt
import PyQt5.QtWidgets as qt
import database as db # файл, соеденяющий БД с приложением
import create_client_fn

app = qt.QApplication([])
window = qt.QWidget()

# НАЧАЛО ФРОНТЭНДА

window.setWindowTitle("Запись клиентов by EevVee's Projects")
window.resize(650, 610)

main_layout = qt.QHBoxLayout()

clients_list_layout = qt.QVBoxLayout() # в составе мэйн
spisok_nadpis = qt.QLabel("Список клиентов:")
clients_list = qt.QListWidget()
clients_list_layout.addWidget(spisok_nadpis)
clients_list_layout.addWidget(clients_list)

but_style = "background-color: rgb(173, 99, 219);"

find_clients_layout = qt.QVBoxLayout() # в составе мэйн
create_and_search_layout = qt.QHBoxLayout() # в составе файнд
create_btn = qt.QPushButton("Создать")
create_btn.setStyleSheet(but_style)
create_and_search_layout.addWidget(create_btn)
search_field = qt.QLineEdit()
search_field.setPlaceholderText("Любая инфо о клиенте")
create_and_search_layout.addWidget(search_field)
search_btn = qt.QPushButton("Найти")
search_btn.setStyleSheet(but_style)
create_and_search_layout.addWidget(search_btn)
find_clients_layout.addLayout(create_and_search_layout)
list_of_found_clients_layout = qt.QVBoxLayout() # в составе файнд
list_of_found_clients = qt.QListWidget()
list_of_found_clients_layout.addWidget(list_of_found_clients)
find_clients_layout.addLayout(list_of_found_clients_layout)




menu_of_app = qt.QVBoxLayout() # в составе мейн # создает лэйаут для кнопок с доп разделами.
notes_sv_btn = qt.QPushButton("Заметки\nсупервизий") # заметки супервизий
sess_descrs_btn = qt.QPushButton("Описания\nсессий") # описания сессий
shedule_btn = qt.QPushButton("Расписание") # расписание сессий
notes_sv_btn.setStyleSheet(but_style)
sess_descrs_btn.setStyleSheet(but_style)
shedule_btn.setStyleSheet(but_style)
menu_of_app.addWidget(notes_sv_btn)
menu_of_app.addWidget(sess_descrs_btn)
menu_of_app.addWidget(shedule_btn)

main_layout.addLayout(clients_list_layout)
main_layout.addLayout(find_clients_layout)
main_layout.addLayout(menu_of_app)

# КОНЕЦ ФРОНТЭНДА



create_btn.clicked.connect(create_client_fn.main)










window.setLayout(main_layout)
window.show()
app.exec_()



# 2024 EevVee's Projects ©


create_client_fn.py file:

from PyQt5.QtCore import Qt
import PyQt5.QtWidgets as qt
import database as db
def main():
    window = qt.QWidget()
    window.setWindowTitle("Создать клиента")

    # создаем основной лэйаут
    main_layout = qt.QVBoxLayout()

    # создаем дополнительные лэйауты для ввода данных клиентов(все пренадлежат main_layout)
    l_name_field_layout = qt.QHBoxLayout()
    f_name_field_layout = qt.QHBoxLayout()
    fa_name_field_layout = qt.QHBoxLayout()
    age_field_layout = qt.QHBoxLayout()
    dateofrequest_field_layout = qt.QHBoxLayout()
    relations_field_layout = qt.QHBoxLayout()
    children_field_layout = qt.QHBoxLayout()
    job_field_layout = qt.QHBoxLayout()
    hobby_field_layout = qt.QHBoxLayout()
    request_field_layout = qt.QHBoxLayout()
    ust_kontr_field_layout = qt.QHBoxLayout()
    save_button_layout = qt.QHBoxLayout()

    # создаем поля для информации и кнопку для создания записи
    l_name_field = qt.QLineEdit()
    f_name_field = qt.QLineEdit()
    fa_name_field = qt.QLineEdit()
    age_field = qt.QLineEdit()
    dateofrequest_field = qt.QLineEdit()
    relations_field = qt.QTextEdit()
    children_field = qt.QTextEdit()
    job_field = qt.QTextEdit()
    hobby_field = qt.QTextEdit()
    request_field = qt.QTextEdit()
    ust_kontr_field = qt.QTextEdit()
    save_button = qt.QPushButton("Создать")

    # создаем подписи к полям
    l_name_label = qt.QLabel("Фамилия")
    f_name_label = qt.QLabel("Имя")
    fa_name_label = qt.QLabel("Отчество")
    age_label = qt.QLabel("Возраст")
    dateofrequest_label = qt.QLabel("Дата обращения")
    relations_label = qt.QLabel("Отношения")
    children_label = qt.QLabel("Дети")
    job_label = qt.QLabel("Работа")
    hobby_label = qt.QLabel("Хобби/увлечения")
    request_label = qt.QLabel("Запрос")
    ust_kontr_label = qt.QLabel("Устный контракт")

    # добавляем подписи к соответствующим второстепенным лэйаутам
    l_name_field_layout.addWidget(l_name_label)
    f_name_field_layout.addWidget(f_name_label)
    fa_name_field_layout.addWidget(fa_name_label)
    age_field_layout.addWidget(age_label)
    dateofrequest_field_layout.addWidget(dateofrequest_label)
    relations_field_layout.addWidget(relations_label)
    children_field_layout.addWidget(children_label)
    job_field_layout.addWidget(job_label)
    hobby_field_layout.addWidget(hobby_label)
    request_field_layout.addWidget(request_label)
    ust_kontr_field_layout.addWidget(ust_kontr_label)

    # добавляем поля и кнопку к соответствующим второстепенным лэйаутам
    l_name_field_layout.addWidget(l_name_field)
    f_name_field_layout.addWidget(f_name_field)
    fa_name_field_layout.addWidget(fa_name_field)
    age_field_layout.addWidget(age_field)
    dateofrequest_field_layout.addWidget(dateofrequest_field)
    relations_field_layout.addWidget(relations_field)
    children_field_layout.addWidget(children_field)
    job_field_layout.addWidget(job_field)
    hobby_field_layout.addWidget(hobby_field)
    request_field_layout.addWidget(request_field)
    ust_kontr_field_layout.addWidget(ust_kontr_field)
    save_button_layout.addWidget(save_button)

    # добавляем второстепенные лэйауты к основному
    main_layout.addLayout(l_name_field_layout)
    main_layout.addLayout(f_name_field_layout)
    main_layout.addLayout(fa_name_field_layout)
    main_layout.addLayout(age_field_layout)
    main_layout.addLayout(dateofrequest_field_layout)
    main_layout.addLayout(relations_field_layout)
    main_layout.addLayout(children_field_layout)
    main_layout.addLayout(job_field_layout)
    main_layout.addLayout(hobby_field_layout)
    main_layout.addLayout(request_field_layout)
    main_layout.addLayout(ust_kontr_field_layout)
    main_layout.addLayout(save_button_layout)

    # на этом фронтэнд завершен

    # устанавливаем лэйаут для окна
    window.setLayout(main_layout)

    # отображаем окно
    window.show()

I started the app, clicked the button "Создать", the window is opened and closed at the same moment.


Solution

  • This problem occurs because when the main function finishes executing, the variables defined inside it (like window) are deleted. To fix this issue, you can define the window variable globally in your create_client_fn.py file.

    this's the modified code

    create_client_fn.py
    from PyQt6.QtCore import Qt
    import PyQt6.QtWidgets as qt
    import database as db
    
    # Define a global variable for the window
    window = None
    
    def main():
        global window
        window = qt.QWidget()
        window.setWindowTitle("Создать клиента")
        # Add the rest of your code here to set up the window
        # ...
    

    The rest of your code can remain unchanged. However, I strongly recommend using Object-Oriented Programming (OOP) principles for better structure and maintainability of your application.