我想在按下按钮时运行和终止一个线程

2024-06-28 19:37:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,它应该发送几个数据点通过串行连接到一个arduino,这将控制一些电机移动。我可以单独发送控制信号,也可以通过txt文件发送,该文件将重复运行,直到文件完成。在运行txt文件时,我希望能够像暂停或停止按钮一样退出循环。我认为最好的办法是通过一个线程,我可以关闭。我从来没有做过任何线程之前,我的初步尝试没有工作。下面是发送文件数据的函数。你知道吗

def send_file():
    # Global vars
    global moto1pos
    global motor2pos
    # Set Ready value
    global isready
    # Get File location
    program_file_name = file_list.get('active')
    file_path = "/home/evan/Documents/bar_text_files/"
    program_file = Path(file_path + program_file_name)
    file = open(program_file)
    pos1 = []
    pos2 = []
    speed1 = []
    speed2 = []
    accel1 = []
    accel2 = []
    for each in file:
        vals = each.split()
        pos1.append(int(vals[0]))
        pos2.append(int(vals[1]))
        speed1.append(int(vals[2]))
        speed2.append(int(vals[3]))
        accel1.append(int(vals[4]))
        accel2.append(int(vals[5]))
    # Send file values
    try:
        while isready == 1:
            for i in range(len(pos1)):
                print("Step: " + str(i+1))
                data = struct.pack("!llhhhh", pos1[i], pos2[i], speed1[i], speed2[i], accel1[i], accel2[i])
                ser.write(data)

                try:
                    pos1time = abs(pos1[i]/speed1[i])
                except:
                    pos1time = 0
                try:
                    pos2time = abs(pos2[i]/speed2[i])
                except:
                    pos2time = 0
            time_array = (pos1time, pos2time)
            time.sleep(max(time_array))
            motor1pos = ser.readline()
            motor2pos = ser.readline()
            if i < (len(pos1)-1):
                isready = ord(ser.read(1))
            else:
                isready = 0
except:
    print("Error: data not sent. Check serial port is open")

下面是我希望sendfile命令从中工作的线程命令。你知道吗

def thread():
    try:
        global isready
        isready = 1
        t = threading.Thread(name='sending_data', target=command)
        t.start()
    except:
        print("Threading Error: you don't know what you are doing")

这是我想要终止线程的停止函数:

def stop():
    try:
        global isready
        isready = 0
        t.kill()
    except:
        print("Error: thread wasn't killed")

我知道你不应该杀死一个线程,但数据不是很重要。更重要的是在有东西坏之前把马达停下来。你知道吗

tkinter中的按钮是:

run_file_butt = tk.Button(master = file_frame, text = "Run File", command = thread)

当我点击按钮,程序运行,但停止功能不停止运动。你知道吗


Tags: 文件program线程globalfileinttryexcept
2条回答

我的答案很简单,因为我对线程的简单理解和使用线程的独特环境。我没有按我所希望的方式终止线程,而是在send\u file函数的发送行中添加了另一个条件语句。你知道吗

    while isready == 1:
        for i in range(len(pos1)):
            if motorstop == False:
                print("Step: " + str(i+1))
                #data = struct.pack('!llllhhhhhhhh', pos1[i], pos2[i], pos3[i], pos4[i], speed1[i], speed2[i], speed3[i], speed[4], accel1[i], accel2[i], accel3[i], accel4[i])
                data = struct.pack("!llhhhh", pos1[i], pos2[i], speed1[i], speed2[i], accel1[i], accel2[i])
                ser.write(data)
            else:
                isready = 0
                break

我已经将stop()函数更新为:

def stop():
    try:
        global motorstop
        global t
        motorstop = True
        t.join()
    except:
        print("Error: thread wasn't killed")

我不太清楚它是如何工作的,但它比@stovefl提到的要简单得多。你知道吗

有了这段代码,因为函数基本上只是在休眠,所以它可以运行,但不会发送任何新信息,然后在下一次迭代后将执行.join()。你知道吗

Question: run and kill a thread on a button press

没有所谓的.kill(...
开始使你的def send_file(...成为一个Thread object,它正在等待你的命令。你知道吗

Note: As it stands, your inner while isready == 1: will not stop by using m.set_state('stop').
It's mandatory to start the Thread object inside:

if __name__ == '__main__':
    m = MotorControl()
import threading, time

class MotorControl(threading.Thread):
    def __init__(self):
        super().__init__()
        self.state = {'is_alive'}
        self.start()

    def set_state(self, state):
        if state == 'stop':
            state = 'idle'

        self.state.add(state)

    def terminate(self):
        self.state = {}

    # main function in a Thread object
    def run(self):
        # Here goes your initalisation
        # ...

        while 'is_alive' in self.state:

            if 'start' in self.state:
                isready = 1
                while isready == 1:
                    # Here goes your activity
                    # Simulate activity
                    print('running')
                    time.sleep(2)
                    isready = 0

                self.state = self.state - {'start'}
                self.state.add('idle')

            elif 'idle' in self.state:
                print('idle')
                time.sleep(1)

if __name__ == '__main__':
    m = MotorControl()

    time.sleep(2)
    m.set_state('start')
    time.sleep(3)
    m.set_state('stop')
    time.sleep(3)
    m.set_state('start')

    time.sleep(4)
    m.terminate()
    print('EXIT __main__')

你的tk.Button应该是这样的:

tk.Button(text = "Run File", command = lambda:m.set_state('start'))
tk.Button(text = "Stop File", command = lambda:m.set_state('stop'))
tk.Button(text = "Terminate", command = m.terminate)

相关问题 更多 >