简体   繁体   中英

How to stop a thread in python?

I am a beginner in Python. I use to code with Tkinter . I want to improve my programs with the extension "threading" . However, in some of my programs, if i leave the Tkinter window, the program is still running . I would like to know how stop it . I guess it's the thread which is still running. I tried different ways to close the thread, but the only issue i found is to create an error (and it is not a nice solution according to me) :).

I would like to know if an instruction like the following one exist to stop the thread.

Thread(target=FinTemps).stop()

(I know that 'stop' is not working)

and if it is possible to stop the Thread with a loop 'while' , I tried this and i don't understand why it doesn't work :

import tkinter as tk
from threading import Thread as Th
from time import *

global end
end=False

begining=time()

def screen():
    global end
    while end==False:
        chrono=time()-beginning
        if chrono<5:
            sentence.set("Hey !")
        elif chrono<8:
            sentence.set("What's up ?")

window=tk.Tk()
window.geometry("{}x{}".format(fenêtre.winfo_screenwidth(), window.winfo_screenheight()))
window.title("Test Tkinter & Thread")

sentence=tk.StringVar()
sentence.set("none")
GreatTitle=tk.Label(window, textvariable=sentence, width=500)

Th(target=screen).start()

GreatTitle.pack(expand=1)

window.mainloop()

end=True

Thank you ;) (And sorry if my english is not wonderful (I'm french) or if my code or explainations weren't very understandable or without following traditional presentation).

Have a good day :)

It may be that your while loop checks end too frequent, it may cause race condition when you try to set end to True after the root window is destroyed.

You can try adding a short sleep inside the while loop to reduce the chance of race condition:

while end == False:
    ...
    sleep(0.1)

What you are doing is not safe. tkinter is not thread-safe, and running any tkinter API cross-thread risks corruption of various kinds.

Bright side is, you don't need threads here. In real code, you wouldn't use a thread at all, you'd just schedule the changes to occur on tkinter 's event loop with the after method , simplifying your code to just:

import tkinter as tk

window=tk.Tk()
window.geometry("{}x{}".format(window.winfo_screenwidth(), window.winfo_screenheight()))
window.title("Test Tkinter & Thread")

sentence=tk.StringVar()
sentence.set("none")
GreatTitle=tk.Label(window, textvariable=sentence, width=500)

GreatTitle.pack(expand=1)

window.after(0, sentence.set, "Hey !")        # Happens almost immediately, as in thread case
window.after(5000, sentence.set, "What's up ?")  # Delays five seconds, as in thread case
window.mainloop()

This is also far more efficient than what you had; as written, your thread would spin forever , constantly looping without pause for as long as it was allowed to do so, keeping a core constantly running at 100%; the GUI itself would run slower because it couldn't do much of its work while the other thread held the GIL. Using .after , no meaningful resources are consumed at any time aside from the moment the event fires and the sentence is updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM