2

I want to connect to a telnet device with a button click (PyQt5 interface). Upon pressing the 'Connect' button, the label should change to 'connecting'. The same label should change to 'connected' when a connection is established. It usually takes a few seconds to establish the connection and I want the user to know that the system is attempting to connect. The problem is that the label only gets set to 'connecting' after the connection is established and not immediately so, if I set it to 'connected' after connection is established, the label bypasses the 'connecting' phase and goes from nothing straight to 'connected'.

import sys
from PyQt5 import QtWidgets
import getstats
username='uname'
password='pword'
import telnetlib
HOST = '192.168.0.5'


class Window(QtWidgets.QWidget):

    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.b = QtWidgets.QPushButton('Connect')
        self.l = QtWidgets.QLabel('Not connected')

        h_box = QtWidgets.QHBoxLayout()
        h_box.addStretch()
        h_box.addWidget(self.l)
        h_box.addStretch()

        v_box = QtWidgets.QVBoxLayout()
        v_box.addWidget(self.b)
        v_box.addLayout(h_box)

        self.setLayout(v_box)
        self.setWindowTitle('PyQt5 Lesson 5')

        self.b.clicked.connect(self.btn_click)

        self.show()

    def btn_click(self):
        self.l.setText('connecting')
        tn_connect()

def tn_connect():
    telnet = telnetlib.Telnet(HOST)
    telnet.read_until(b"Password:")
    telnet.write((password + "\n").encode('ascii'))
    telnet.write(("exit\n").encode('ascii'))
    telnet_out = str(telnet.read_all())
    print(telnet_out)
    a_window.l.setText('connected')



app = QtWidgets.QApplication(sys.argv)
a_window = Window()
sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
blitz
  • 623
  • 5
  • 18

1 Answers1

3

To force the update of the GUI you must call processEvents()

def btn_click(self):
    self.l.setText('connecting')
    QtWidgets.qApp.processEvents()
    tn_connect()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241