【问题标题】:Problem connecting buttons to a function (PyQT5) [duplicate]将按钮连接到功能时出现问题(PyQT5)[重复]
【发布时间】:2023-03-23 17:21:02
【问题描述】:

我是 Python 3.8 和 PyQT5 的新手,我正在尝试使用 GUI 制作应用程序。

我创建了一个带有两个 QLineEdit(用户和密码)的登录表单。一旦用户单击“登录”按钮,我想检查用户作为用户/密码输入的内容是否在使用其他文件中的函数在数据库中。我为表单创建的类与下一个类似:

# Where the check function for the password is
from CLBK_CheckPassword import CheckPassword
from PyQt5 import QtWidgets

class W_Password(QtWidgets.QWidget):

    def __init__(self, App):
    
        super(W_Password,self).__init__()
    
        # Set the window title and size
        WindowHeight = 400
        WindowWeight = WindowHeight/3
        self.setWindowTitle("Login Window")
        self.resize(WindowHeight,WindowWeight)
    
        # Text box
        self.Input_User = QtWidgets.QLineEdit()
        self.Input_Password = QtWidgets.QLineEdit()
        self.Input_Password.setEchoMode(QtWidgets.QLineEdit.Password)

        # Button
        self.Button_Login = QtWidgets.QPushButton("Login")
        self.Button_Login.clicked.connect(CheckPassword())

        # Layout and items positioning
        self.Layout = QtWidgets.QGridLayout(self)
        self.Layout.addWidget(self.Button_Login,3,2,1,2)
        self.Layout.addWidget(self.Label_User,0,0,1,1)
        self.Layout.addWidget(self.Input_User,0,1,1,3)
        self.Layout.addWidget(self.Label_Password,1,0,1,1)
        self.Layout.addWidget(self.Input_Password,1,1,1,3)

这段代码有两个问题:

  1. 创建并显示表单后,会自动执行“CheckPassword()”函数(仅当用户按下按钮时才会执行)。
  2. 第二个问题是函数执行后出现以下错误:TypeError: argument 1 has unexpected type 'NoneType'

【问题讨论】:

    标签: python python-3.x pyqt pyqt5


    【解决方案1】:

    问题 1

    您应该将CheckPassword 函数作为参数传递给事件监听器clicked.connect

    所以

    self.Button_Login.clicked.connect(CheckPassword())
    

    行更改为:

    self.Button_Login.clicked.connect(CheckPassword)
    

    问题 2

    您的函数CheckPassword 似乎至少需要一个参数。所以你必须稍微改变一下逻辑。

    你可以使用lambda表达式:

    self.Button_Login.clicked.connect(lambda: (CheckPassword(THE_PARAMETER)))
    

    编辑

    回答:如果'CheckPassword'函数返回一些东西怎么办?

    正如musicamante 提到的,您可以使用另一种方法来运行您的函数并捕获返回值,例如:

    # Where the check function for the password is
    from CLBK_CheckPassword import CheckPassword
    from PyQt5 import QtWidgets
    
    class W_Password(QtWidgets.QWidget):
    
        def __init__(self, App):
        
            super(W_Password,self).__init__()
        
            ...
            self.Button_Login.clicked.connect(lambda: (self.checher()))
    
            ...
    
        def checher(self):
            value = CheckPassword(THE_PARAMETER)
            # Do something with value
    

    【讨论】:

    • 非常感谢,它完美运行!我想到了另一个问题:如果函数“CheckPassword”返回一些东西怎么办?是否可以将其保存在变量中?
    • @Ralk 连接函数的返回值总是被忽略。为 W_Password 创建另一个方法并将其连接到 clicked 信号,然后您可以将返回值的引用创建为实例属性。
    猜你喜欢
    • 2020-05-15
    • 2021-03-05
    • 2017-07-07
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多