简体   繁体   中英

How to use while loop in this pyqt5 window

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_())

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM