如何在Python中比较PyQt5中的字符串?

问题描述 投票:0回答:1

我想在PyQt5中使用GUI应用程序,如果您单击按钮,则标签中会出现一些随机文本。如果该随机文本等于Whats up?,则它将在终端中键入True。否则,它将打印False

但是我每次都得到False ...

这是我的代码:

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
import sys
import random

lis = ["Hello world", "Hey man", "Yo buddy", "Go to hell", "Whats up?"]

class MyWindow(QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.initUI()
        self.setGeometry(200,200,300,300) 
        self.setWindowTitle("WhatsApp Sheduled")

    def initUI(self):
        self.label = QLabel(self)
        self.label.setText("My first label")
        self.label.move(120, 120)

        self.b1 = QtWidgets.QPushButton(self)
        self.b1.setText("Click here")
        self.b1.clicked.connect(self.clicked)

    def clicked(self):
        self.label.setText(random.choice(lis))
        if self.label == "Whats up?":
            print("True")
        else:
            print("False")

def clicked():
    print("Clicked!")

def main():
    app = QApplication(sys.argv)
    win = MyWindow()

    win.show()
    sys.exit(app.exec_())

main()  # It's important to call this function

任何帮助将不胜感激...

[请告诉我该怎么做。我是GUI的新手,所以了解的不多。

python python-3.x if-statement pyqt pyqt5
1个回答
1
投票

您只是忘记使用其text访问器功能:

    if self.label.text() == "Whats up?":

((请注意,这是一个函数,因此在文本后加上括号)。

© www.soinside.com 2019 - 2024. All rights reserved.