tkinter threading unblock GUI ( check if the thread exists)

from tkinter import *
from tkinter.ttk import *
import time
import threading
import requests
from bs4 import BeautifulSoup

url3 = 'http://stackoverflow.com/questions/31241112/blocking-tkinter-interface-until-thread-finishes-its-task'

class Interface:
    def __init__(self, master):
        self.mutex = threading.Lock()
        self.m_list = []
        self.master = master
        self.browse_button= Button (master, text="Browse", command=self.browser)
        self.browse_button.pack()
        # Create an indeterminate progressbar here but don't pack it.
        # Change the maximum to change speed. Smaller == faster.
        self.progressbar = Progressbar(mode="indeterminate", maximum=20)

    def browser (self):
        self.start = time.time()
        # set up thread to do work in
        self.thread = threading.Thread(target=self.read_file, args=("filename",))
        # disable the button
        self.browse_button.config(state="disabled")
        # show the progress bar
        self.progressbar.pack()
        # change the cursor
        self.master.config(cursor="wait")
        # force Tk to update
        self.master.update()

        # start the thread and progress bar
        self.thread.start()
        self.progressbar.start()
        # check in 50 milliseconds if the thread has finished
        self.master.after(50, self.check_completed)

    def check_completed(self):
        if self.thread.is_alive():
            # if the thread is still alive check again in 50 milliseconds
            self.master.after(50, self.check_completed)
        else:
            # if thread has finished stop and reset everything
            self.progressbar.stop()
            self.progressbar.pack_forget()
            self.browse_button.config(state="enabled")
            self.master.config(cursor="")
            self.master.update()

            # Call method to do rest of work, like displaying the info.
            self.display_file()

    def read_file (self, filename):
        # time.sleep(7)  # actually do the read here
        self.mutex.acquire()
        try:
            resp = requests.get(url3)

            soup = BeautifulSoup(resp.content, 'html.parser')

            for link in soup.select('a'):
                self.m_list.append(link.get('href'))
        finally:
            self.mutex.release()

    def display_file(self):
        new_list = []
        for i in self.m_list:
            # print type(i) # unicode
            new_list.append(str(i).strip('\n'))

        self.cp(new_list)

    def cp(self, new_list):
        tp = Toplevel(self.master)
        text = Text(tp)
        text.pack()

        text.insert(1.0, '\n'.join(new_list))

        print time.time() - self.start



window = Tk()
starter = Interface(window)
window.mainloop()
posted @ 2017-03-16 23:28  idlewith  阅读(449)  评论(0编辑  收藏  举报