【问题标题】:How to use while loop in this pyqt5 window如何在这个 pyqt5 窗口中使用 while 循环
【发布时间】:2020-01-31 08:01:22
【问题描述】:

这是我在这里的第一个问题。我已经研究了一些类似的问题,但它并没有真正帮助我处理我自己的代码(或者我无法将可能的解决方案应用于我的代码,我不确定)。

我有这段代码在我运行它时在窗口中显示时间,但它没有更新,如果我想查看当前时间,我必须再次运行它。我试图在某处包含 while 循环,但我不能。通常当我使用漂亮的汤或硒从网站获取数据时,我可以将它们放在一个while循环中并让它们毫无问题地运行,但我无法在这个pyqt5窗口中实现它。我能做什么做吗?

import sys
import time
from PyQt5 import QtWidgets,QtCore
import requests
from bs4 import BeautifulSoup

class Window(QtWidgets.QWidget):

    def __init__(self):
        super().__init__()
        self.init_ui()
    def  init_ui(self):
        self.textfield = QtWidgets.QLabel("")
        sonuc = self.gettime()

        v_box = QtWidgets.QVBoxLayout()

        v_box.addWidget(self.textfield)
        v_box.addStretch()

        h_box = QtWidgets.QHBoxLayout()

        h_box.addStretch()
        h_box.addLayout(v_box)
        h_box.addStretch()

        self.setLayout(h_box)
        self.setWindowTitle("Time")
        self.show()
    def gettime(self):

        url = "https://onlinesaat.web.tr/saat-kac/"
        a = requests.get(url)
        b = a.content
        soup = BeautifulSoup(b,"html.parser")

        for i in soup.find_all("span",{"id":"lbl-time"}):
            self.textfield.setText(i.text)

app = QtWidgets.QApplication(sys.argv)
window = Window()
sys.exit(app.exec_())

【问题讨论】:

    标签: python pyqt5


    【解决方案1】:

    使用QTimer

    例如,这会每 1000 毫秒(1 秒)调用一次您的 gettime 函数

    ...
    def  init_ui(self):
        self.textfield = QtWidgets.QLabel("")
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.gettime)
        timer.start(1000)
    

    【讨论】:

    • 非常感谢,它成功了!但是窗口每秒钟都变得迟钝,我们能做些什么呢?没什么大不了的。
    • 因为您从 API 获取时间并且需要一些时间才能获得结果。改为使用 python 内置函数来检索当前时间。 programiz.com/python-programming/datetime/current-time
    猜你喜欢
    • 2019-06-09
    • 1970-01-01
    • 2022-08-23
    • 2021-03-27
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多