Why cant I view updates to a label while making an HTTP request in Python

2024/10/15 8:21:12

I have this code :

def on_btn_login_clicked(self, widget):email = self.log_email.get_text()passw = self.log_pass.get_text()self.lbl_status.set_text("Connecting ...")params = urllib.urlencode({'@log_email': email, '@log_pass': passw, '@action': 'login', '@module': 'user'})headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}conn = httplib.HTTPConnection("website.com")self.lbl_status.set_text("Logging in ...")conn.request("POST", "/ajax.php", params, headers)response = conn.getresponse()print response.statusself.lbl_status.set_text("")data = response.read()      print dataconn.close()

The self.lbl_status doesn't change till the request is finished, so it displays nothing due to the last set_text function.

Why is this happening, and how to avoid/fix that?

Answer

Below is a working example of a simple downloader for illustration purposes only. You need to use multi-threading if you want your GUI to be responsive and not freeze while you do some long running or blocking operation. I put this example together based on this stack overflow question and this excellent article Using threads in PyGTK. The default url an Ubuntu iso will take a while to download and should provide a good demonstration . You can enter any url you want when prompted it will download and save the file in the current directory.

from threading import Thread
import time
import gtk, gobject, urllibURL = 'http://releases.ubuntu.com//precise/ubuntu-12.04.1-desktop-i386.iso'def download(url):filename = url.split('/')[-1]out = open(filename, 'wb')gobject.idle_add(label.set_text, "connecting...")f = urllib.urlopen(url)buffer = f.read(1024)counter = 0while buffer:counter += len(buffer)out.write(buffer)msg = "downloaded {0:,} bytes".format(counter)gobject.idle_add(label.set_text, msg)buffer = f.read(1024)out.close()gobject.idle_add(label.set_text, "download complete")def clicked(button):url = entry.get_text()Thread(target=download, args=(url,)).start()gtk.gdk.threads_init()
win = gtk.Window()
win.set_default_size(400, 100)
entry = gtk.Entry()
entry.set_text(URL)
label = gtk.Label("Press the button")
button = gtk.Button(label="Download")
button.connect('clicked', clicked)box = gtk.VBox()
box.pack_start(entry)
box.pack_start(label)
box.pack_start(button)
win.add(box)win.show_all()gtk.main()
https://en.xdnf.cn/q/117852.html

Related Q&A

plotting multiple graph from a csv file and output to a single pdf/svg

I have some csv data in the following format.Ln Dr Tag Lab 0:01 0:02 0:03 0:04 0:05 0:06 0:07 0:08 0:09 L0 St vT 4R 0 0 0 0 0 0…

parallel python: just run function n times [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 9…

how to specify the partition for mapPartition in spark

What I would like to do is compute each list separately so for example if I have 5 list ([1,2,3,4,5,6],[2,3,4,5,6],[3,4,5,6],[4,5,6],[5,6]) and I would like to get the 5 lists without the 6 I would do …

Keeping just the hh:mm:ss from a time delta

I have a column of timedeltas which have the attributes listed here. I want the output in my pandas table to go from:1 day, 13:54:03.0456to:13:54:03How can I drop the date from this output?

How to return the index of numpy ndarray based on search?

I have a numpy 2D array, import numpy as np array1 = array([[ 1, 2, 1, 1],[ 2, 2, 2, 1],[ 1, 1, 1, 1],[1, 3, 1, 1],[1, 1, 1, 1]])I would like to find the element 3 and know its location. So,…

Python:Christmas Tree

I need to print a Christmas tree that looks like this:/\ / \ / \Here is my code so far:for count in range (0,20):variable1 = count-20variable2 = count*2print({0:{width1}}{1:{width2}} .format(/,\\,…

Send back json to client side

I just started developing with cherrypy, so I am struggling a little bit. In client side I am selecting some data, converting it to json and sending to server side via post method. Then I am doing a fe…

Can I use PyInstaller from Python 2.7 to compile an executable for a Python 3 script?

So, I tried installing PyInstaller in my Python 3.4 dir but, for some reason, Ive been getting errors and Im not able to install it. I however, do have a working PyInstaller in my Python 2.7 dir. I nee…

exporting different lists to .txt in python

I have a few lists which I all want to export to the same .txt file. So far I only export 3 of the lists usingmy_array=numpy.array(listofrandomizedconditions) my_array2=numpy.array(inputsuser) my_arra…

Retrieving information from dictionary

Im having hard time trying to read my dictionary variable. Python keeps throwing the following error:TypeError: string indices must be integersThis is a sample that should give you an idea of what my p…