无法使用PyQt4打开新窗口

时间:2018-07-20 00:32:56

标签: python pyqt pyqt4 qwidget

我编写了此代码..当我满足要求并按登录时,应该会打开一个新窗口,但是当我打开该窗口时,它就会消失..我看到了很多使用OOP的代码,但我不理解它们所以我需要任何人给我一个简单的解决方案

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
import os
import shutil
app = QApplication(sys.argv)
main_window = QWidget()
main_window.setWindowTitle("Keep It Safe V1.5")
main_window.setWindowIcon(QIcon('lock.png'))
main_window.resize(350, 180)
main_window.move(500, 200)
login_btn = QPushButton('Login', main_window)
login_btn.resize(150, 30)
login_btn.move(100, 120)
User = QLineEdit(main_window)
User.resize(250, 30)
User.move(50, 10)
User.setPlaceholderText('Enter your user name')
password = QLineEdit(main_window)
password.resize(250, 30)
password.move(50, 60)
password.setPlaceholderText('Enter your passsword')
password.setEchoMode(QLineEdit.Password)
check = QCheckBox(main_window, text="I accept the terms and policies")
check.move(50, 95)
def login_check():
    user = User.text()
    Pass = password.text()
    if user == "Admin" and Pass == "admin" and check.isChecked():
        print("Clicked")
        sec_win =QWidget()
        l = QLabel(sec_win , text = "second window opened")
        sec_win.show()
    else:
        fai = QMessageBox.warning(main_window, "Error", "Incorrect user name or passwprd")
login_btn.clicked.connect(login_check)
main_window.show()
app.exec_()

1 个答案:

答案 0 :(得分:0)

在函数内创建的变量是局部变量,因此在执行完毕后将被删除,而sec_win则将显示该变量,但稍后将其删除,解决方案是在之前和之后创建它仅在必要时显示它。

import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication(sys.argv)
main_window = QWidget()
main_window.setWindowTitle("Keep It Safe V1.5")
main_window.setWindowIcon(QIcon('lock.png'))
main_window.resize(350, 180)
main_window.move(500, 200)
login_btn = QPushButton('Login', main_window)
login_btn.resize(150, 30)
login_btn.move(100, 120)
User = QLineEdit(main_window)
User.resize(250, 30)
User.move(50, 10)
User.setPlaceholderText('Enter your user name')
password = QLineEdit(main_window)
password.resize(250, 30)
password.move(50, 60)
password.setPlaceholderText('Enter your passsword')
password.setEchoMode(QLineEdit.Password)
check = QCheckBox(main_window, text="I accept the terms and policies")
check.move(50, 95)

sec_win =QWidget()

def login_check():
    user = User.text()
    Pass = password.text()
    if user == "Admin" and Pass == "admin" and check.isChecked():
        print("Clicked")
        l = QLabel(sec_win , text = "second window opened")
        sec_win.show()
    else:
        fai = QMessageBox.warning(main_window, "Error", "Incorrect user name or passwprd")

login_btn.clicked.connect(login_check)
main_window.show()
sys.exit(app.exec_())