Home > database >  How To Fix Python Threading Module Problem
How To Fix Python Threading Module Problem

Time:02-13

In the code below, when I press Button 1, the application does not respond and I cannot use other Button 2. Threading module was required for this. I have created Threads for Threadingle main() and process(), but when the program opens and I press Button 1, the application does not respond and I cannot press Button 2. What's the problem?

from tkinter import *
import threading

def process():
    while True:
        print("Hello World")
processThread = threading.Thread(target=process)

def main():

    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton=Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red",fg="white", width="15", command=processThread.run)
    recButton.place(x=15,y=10)

    stopButton=Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange",fg="white", width="15", command="")
    stopButton.place(x=15,y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()
mainThread = threading.Thread(target=main)
mainThread.start()

CodePudding user response:

use processThread.start to start the thread instead of processThread.run infact processThread.run will just call the process method and which will not return control to your event loop hence application goes wild

command=processThread.start

from tkinter import *
import threading

def process():
    while True:
        print("Hello World")
processThread = threading.Thread(target=process)

def main():

    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton=Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red",fg="white", width="15", command=processThread.start)
    recButton.place(x=15,y=10)

    stopButton=Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange",fg="white", width="15", command="")
    stopButton.place(x=15,y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()
mainThread = threading.Thread(target=main)
mainThread.start()

CodePudding user response:

So how do I stop a running Thread. Because what I want is that it starts when I press Button 1, stops when I press Button 2.

  • Related