Display a label while pressing the button in my GUI

Peter Otten __peter__ at web.de
Mon Jan 30 04:31:01 EST 2017


hmmeeranrizvi18 at gmail.com wrote:

> Hello Guys,
> Here i am creating a GUI which will act as a search engine that will find
> the results from the browser and save the results as a xls file. When i
> typed something in my search box and click the (GO)button.It should
> display search in progress.when the file is saved it should display done.
> How to do that? My button gets hung for a seconds.We should give any
> timeout for that?

Move the actual processing into another thread and have it communicate with 
your GUI through a Queue. Here's a sketch:

import Queue
import threading

from Tkinter import *
import mechanize

def clear_search(event):
    search.delete(0, END)

def start_search():
    thread = threading.Thread(
        target=fun,
        args=(search.get(),)
    )
    thread.setDaemon(True)
    thread.start()
    root.after(100, check_state)

def fun(new):
    queue.put("searching")
    url = "http://duckduckgo.com/html"
    br = mechanize.Browser()
    br.set_handle_robots(False)
    br.open(url)
    br.select_form(name="x")
    br["q"] = str(new)
    res = br.submit()
    queue.put("writing result")
    content = res.read()
    with open("result1.xls", "w") as f:
        f.write(content)
    queue.put("done")

def check_state():
    while True:
        try:
            message = queue.get_nowait()
        except Queue.Empty:
            break
        state_info["text"] = message
        if message == "done":
            return
    root.after(100, check_state)

queue = Queue.Queue()
root = Tk()

top_findings = Label(root, text="Top Findings:", font="-weight bold")
top_findings.pack()

search = Entry(root, width=100)
search.insert(0, "Enter the value to search")

# Did you see Christian Gollwitzer's post?
search.bind("<FocusIn>", clear_search)

search.pack()

go_button = Button(root, text="GO", width=5, command=start_search)
go_button.pack()

state_info = Label(root)
state_info.pack()

root.mainloop()




More information about the Python-list mailing list