不确定我是否正在正确运行线程

时间:2019-02-07 16:14:07

标签: python python-multithreading

我正在运行一个线程来不断监视温度,并更新其他函数需要据此执行其任务的全局变量。现在一切正常,我可以接受。但是我想伸出援手,看看是否有人有更聪明的方法来保持这种状态直到主循环结束。这是启动线程的方式...

thread1 = Thread(target = test)
try:
    thread1.start()
except (KeyboardInterrupt, SystemExit):
    thread1.stop()
    sys.exit()

我想我可以编写一个小脚本来使其运行。抱歉...

import time
import tkinter
from tkinter import *
from threading import Thread

root = Tk()

timer = True

global counter
counter = 0
var1 = StringVar()
var1.set(counter)

def test():
    global counter
    while timer:
        counter += 1
        var1.set(counter)
        root.update
        time.sleep(1)

testtext = Label(root,textvariable=var1,font='Consolas 24 bold')
testtext.grid(row=1,column=1,sticky="N,S,E,W",padx=10,pady=0)
testtext2 = Label(root,text="SECONDS",font='Consolas 18 bold')
testtext2.grid(row=2,column=1,sticky="N,S,E,W",padx=10,pady=0)

thread1 = Thread(target = test)
try:
    thread1.start()
except (KeyboardInterrupt, SystemExit):
    thread1.stop()
    sys.exit()

root.mainloop()

如您所见,关闭窗口后,线程确实结束了,但不是很干净。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

Tkinter支持协议处理程序。

最常用的协议称为WM_DELETE_WINDOW,用于定义当用户使用窗口管理器显式关闭窗口时发生的情况。

import time
import tkinter
from tkinter import *
from threading import Thread

def on_closing():
    thread1.close()
    root.destroy()

def test():
    global counter
    while timer:
        counter += 1
        var1.set(counter)
        root.update
        time.sleep(1)

root = Tk()

timer = True

global counter
counter = 0
var1 = StringVar()
var1.set(counter)

testtext = Label(root,textvariable=var1,font='Consolas 24 bold')
testtext.grid(row=1,column=1,sticky="N,S,E,W",padx=10,pady=0)
testtext2 = Label(root,text="SECONDS",font='Consolas 18 bold')
testtext2.grid(row=2,column=1,sticky="N,S,E,W",padx=10,pady=0)

global thread1 = Thread(target = test)
try:
    thread1.start()
except (KeyboardInterrupt, SystemExit):
    thread1.stop()
    sys.exit()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()

基本上,该程序侦听close事件并决定在functuon on_closing()中杀死该窗口时该怎么做。

答案 1 :(得分:1)

知道了。谢谢Daniel Reyhanian向我指出了

root.protocol(“ WM_DELETE_WINDOW”,on_closing)

东西。以前从未见过。

这是使用os._exit(1)

的最后一位
import os
import time
import tkinter
from tkinter import *
from threading import Thread

root = Tk()

timer = True

global counter
counter = 0
var1 = StringVar()
var1.set(counter)

def on_closing():
    os._exit(1)

def test():
    global counter
    while timer:
        counter += 1
        var1.set(counter)
        root.update
        time.sleep(1)

testtext = Label(root,textvariable=var1,font='Consolas 24 bold')
testtext.grid(row=1,column=1,sticky="N,S,E,W",padx=10,pady=0)
testtext2 = Label(root,text="SECONDS",font='Consolas 18 bold')
testtext2.grid(row=2,column=1,sticky="N,S,E,W",padx=10,pady=0)

thread1 = Thread(target = test)
thread1.start()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()