How can I kill a thread with python

Tags: , , ,



I am making a random number guessing game with GUI (Tkinter) and this comes up RuntimeError: threads can only be started once. I’m trying to kill the thread but I can’t find any way. Here’s the code:

def main(c):
    global max_num, number, guess_num, enter, l1, t1

    if c <= 5:
        messagebox.showerror(title='Import error', message='Please add a bigger number than 5')
        max_num.delete(0, END)
    else:
        number = random.randrange(1, c+1)
        print(number)

        t1 = threading.Thread(target=lambda: process(int(guess_num.get())))
        l1 = Label(root, text='Whats the number?')
        guess_num = Entry(root, bd=3)
        enter = Button(root, text='Enter', command=t1.start)

        l1.grid(row=2)
        guess_num.grid(row=3)
        enter.grid(row=3, column=1)

def process(answer):
        global number

        if number == answer:
            result = Label(root, text='Correct Answer!')

            result.grid(row=4)
            guess_num.destroy()
            enter.destroy()
            l1.destroy()

        else:
            if answer > number:
                wrong_result = Label(root, text='Wrong Answer! Your answer is bigger than the random number', fg='red')

            elif answer < number:
                wrong_result = Label(root, text='Wrong Answer! Your answer is smaller than the random number', fg='red')

            wrong_result.grid(row=4)
            time.sleep(3)
            wrong_result.destroy()


In the first function (main) is where I call the Thread and in the second function (process) is where I want to kill the Thread.

Answer

The error is trying to tell you that passing command=t1.start will result in calling start() on the same t1 instance every time the button is pressed. In Python, you cannot call thread.start() multiple times on the same thread instance. Change the following lines:

        ...
        print(number)

        t1 = threading.Thread(target=lambda: process(int(guess_num.get())))
        l1 = Label(root, text='Whats the number?')
        guess_num = Entry(root, bd=3)
        enter = Button(root, text='Enter', command=t1.start)
        ...

To

        ...
        print(number)

        def process_in_thread():
            t1 = threading.Thread(target=lambda: process(int(guess_num.get())))
            t1.start()

        l1 = Label(root, text='Whats the number?')
        guess_num = Entry(root, bd=3)
        enter = Button(root, text='Enter', command=process_in_thread)
        ...



Source: stackoverflow