Home > Mobile >  Python threaded process does not prevent 'Not responding'
Python threaded process does not prevent 'Not responding'

Time:08-01

I'm trying to implement a threaded process to prevent my program from going into a 'Not responding' state, but it isn't working. After five seconds the program locks up until the process completes and the progressbar jumps to 100%.

from tkinter import *
import tkinter as tk
from tkinter import ttk
import time
import threading

root = tk.Tk()

def begin_program():
    # Do a lot of other stuff first

    new_thread = threading.Thread(target=longprocess, daemon=True)
    new_thread.start()

    total_time = 10
    start_time = time.time()
    print('start_time: '   str(start_time))
    while new_thread.is_alive():
        current_time = time.time()
        elapsed_time = current_time - start_time
        progress = round(elapsed_time * 100 / total_time)
        print("progress: "   str(progress))
        progressbar['value'] = progress
        root.update_idletasks()
    progressbar.stop()

def longprocess():
    time.sleep(10)

progressbar = ttk.Progressbar(root, orient=HORIZONTAL, length=300, mode='determinate')
progressbar.pack(padx=20, pady=20)

button = Button(root, text='Start', command=begin_program)
button.pack(pady=20)

root.mainloop()

Any insight into why this is happening would be greatly appreciated.

CodePudding user response:

The while loop in begin_program keeps the main thread spinning in a busy-loop even though you're processing events.

You could e.g. put that section of code (but without the while) in a callback activated by after ever 50 ms or so. That would make it fit into the event-driven nature of a tkinter program.

  • Related