Lorenz Weidinger
Lorenz Weidinger

Reputation: 71

Tkinter Threading Error: RuntimeError: threads can only be started once

I have created a tkinter GUI in the following structure:

import tkinter as tk
import threading

class App:
    def __init__(self, master):
        self.display_button_entry(master)

    def setup_window(self, master):
        self.f = tk.Frame(master, height=480, width=640, padx=10, pady=12)
        self.f.pack_propagate(0)

    def display_button_entry(self, master):
        self.setup_window(master)
        v = tk.StringVar()
        self.e = tk.Entry(self.f, textvariable=v)
        buttonA = tk.Button(self.f, text="Cancel", command=self.cancelbutton)
        buttonB = tk.Button(self.f, text="OK", command=threading.Thread(target=self.okbutton).start)
        self.e.pack()
        buttonA.pack()
        buttonB.pack()
        self.f.pack()

    def cancelbutton(self):
        print(self.e.get())
        self.f.destroy()

    def okbutton(self):
        print(self.e.get())


def main():
    root = tk.Tk()
    root.title('ButtonEntryCombo')
    root.resizable(width=tk.NO, height=tk.NO)
    app = App(root)
    root.mainloop()

main()

I want to prevent the GUI from freezing when running a function (in the example code it's the function of the ok-button). For that I found the solution of using the thread-module as best practice. But the problem is that when I want to run the code once again, python returns this traceback:

RuntimeError: threads can only be started once

I'm totally aware of the problem that threads can be only starten once as stated in the error message. My question is: How can I stop a thread to start it a second time or does anybody has a better workaround for preventing the GUI from freezing and pressing a button/running a function multiple times?

BR and thank you Lorenz

Upvotes: 1

Views: 1762

Answers (1)

acw1668
acw1668

Reputation: 46678

Your code will only create one thread and assign its start function reference to command option. Therefore same start() function will be called whenever the button is clicked.

You can use lambda instead:

command=lambda: threading.Thread(target=self.okbutton).start()

Then whenever the button is clicked, a new thread will be created and started.

Upvotes: 7

Related Questions