Warm tip: This article is reproduced from stackoverflow.com, please click
pyqt5 python

How to use while loop in this pyqt5 window

发布于 2020-03-27 15:43:35

This is my first question here.I have looked into some similar questions but it didn't really help me with my own code(or i failed to apply the possible solution to my code ,im not sure).

I have this code that shows the time in a window when i run it but it doesn't update and if i want to see the current time i have to run it again.I have tried to include while loop somewhere but i couldn't.Normally when im fetching data from websites using beautiful soup or selenium , i am able to put them in a while loop and keep them running without any problem but i couldn't make it happen in this pyqt5 window.What can i do ?

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_())
Questioner
mertyilmazdeu
Viewed
18
ryanhz 2020-01-31 16:48

use QTimer

for example, this calls your gettime function every 1000milliseconds(1s)

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