首页 > 解决方案 > 如何在 Python 中比较 PyQt5 中的字符串?[解决了]

问题描述

我想制作一个 GUI 应用程序PyQt5,如果你点击一个按钮,那么标签中会出现一些随机文本。如果该随机文本等于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 新手,所以不太了解。

标签: pythonpython-3.xif-statementpyqtpyqt5

解决方案


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

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

(请注意,它是一个函数,因此文本后面有括号)。

[编辑]回答你的第二个问题:

def initUI(self):
#...
        self.label2 = QLabel(self)
        self.label2.setText("Guido")
        self.label2.move(0, 120)
        self.label2.setVisible(False)

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

推荐阅读