0

I'm rewriting this Tkinter app to pyqt5. I'm using asyncio for refreshing the Tkinter window every time because Im fetching an url repeatedly, and it requires self.update() to be called every time so the window doesn't freeze.

from tkinter import *
import asyncio
import aiohttp
    
class App(Tk):
    def __init__(self, loop):
        super().__init__()
        self.title("GUI Client")
        self.loop = loop
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.tasks = []
        self.tasks.append(loop.create_task(self.rotator(1/60)))
        self.tasks.append(loop.create_task(self.updater()))

    async def rotator(self, interval):
        while await asyncio.sleep(interval, True):
            self.response = await get()
            print(self.response)
            
    async def updater(self):
        while await asyncio.sleep(0, True):                
            self.update()

    def close(self):
        for task in self.tasks:
            task.cancel()
        self.loop.stop()
        self.destroy()   

async def get ():
    async with aiohttp.ClientSession() as session:
        async with session.post('https://jsonplaceholder.typicode.com/posts', json={
    'title':'foo',
    'body':'bar',
    'userId':1
}, headers = {'Content-type': 'application/json; charset=UTF-8'}) as resp:
            data = await resp.json()
            return data    

loop = asyncio.get_event_loop()
app = App(loop)
loop.run_forever()
loop.close()

This is the pyqt5 gui but it doesn't work, I don't know if I'm using the imports well because I'm getting

QWidget: Must construct a QApplication before a QWidget

from PyQt5 import QtCore, QtGui, QtWidgets
import asyncio

class App(QtWidgets.QMainWindow):

    def __init__(self, loop):
        super().__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("GUI")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.show()
        self.loop = loop
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.tasks = []
        self.tasks.append(loop.create_task(self.updater()))

    async def updater(self):
        while await asyncio.sleep(0, True):                
            self.update()
            
    def close(self):
        for task in self.tasks:
            task.cancel()
        self.loop.stop()
        self.destroy() 

loop = asyncio.get_event_loop()
app = App(loop)
loop.run_forever()
loop.close()

1 Answer 1

1

I added the quamash package to combine pyQt5 and asyncio.

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import quamash
import aiohttp
import asyncio

class App(QWidget):

    run = 0
    response = ''
    def __init__(self, loop):
        super().__init__()

        btn = QPushButton('Start', self)
        btn.resize(btn.sizeHint())
        btn.move(50, 50)
        btn.clicked.connect(self.start)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('GUI')    
        self.show()
        self.loop = loop
        self.tasks = []
        self.tasks.append(loop.create_task(self.rotator()))
        
    async def rotator(self):
        while await asyncio.sleep(0, True):
            if (self.run == 1):
                self.response = await get()
                print(self.response)
                  
    def start (self):
        self.run = 1            
    
async def get ():
    async with aiohttp.ClientSession() as session:
        async with session.post('https://jsonplaceholder.typicode.com/posts', json={
        'title':'foo',
        'body':'bar',
        'userId':1
    }, headers = {'Content-type': 'application/json; charset=UTF-8'}) as resp:
            data = await resp.json()
            return data
      
app = QApplication(sys.argv)
loop = quamash.QEventLoop(app)
asyncio.set_event_loop(loop)

with loop:
    window = App(loop)
    window.show()
    loop.run_forever()

It isn't necessary to update the window in pyQt5 app.

Removed below code:

self.tasks.append(loop.create_task(self.updater()))

    async def updater(self):
        while await asyncio.sleep(0, True):                
            self.update()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.