python3:如何设置任意键控制程序运行、停止和退出

总体思路:设置一个线程,用来实时获取用户的输入,然后每次播放完后根据对应输入进行播放停止、继续和退出操作。

这里以图片播放控制为例,不多说,直接上代码:

import cv2 as cv
import os
from threading import Thread
import sys

command_key = 'o' # 此键用来控制图片播放、停止以及程序退出

# 定义一个实时获取键盘输入的程序
def get_command(): 
    global command_key # 因为后续要对这个command_key 进行修改,所以这里需要声明成global
    command_key = input() # 获取输入
    get_command() # 获取下一次输入
 
# 定义一个线程   
thd = Thread(target = get_command) #线程定义
thd.start() # 开启线程

#这个地方设置了一个路径和一个图片播放窗口
path_train = "D:/Datasets/miniimagenet/train/"
cv.namedWindow("Train", cv.WINDOW_FREERATIO) 

#显示在所设置路径下的所有图片, filename这里仅为文件的文件名,如1.jpg
for filename in os.listdir(path_train):
    show_path = path_train + filename # 加一个根目录编程图片的路径
    image = cv.imread(show_path) # 读取图片
    cv.imshow("Train", image) # 显示图片
    cv.waitKey(500) # 设置刷新时间为500ms
    
    # 下面这些为命令判断, s表示播放暂停,c表示继续播放,表示退出
    if command_key == 's':           
        print("Displaying stopped! Press c to start!")
        stop_flag = True
        while stop_flag:
            if command_key == 'c':
                stop_flag = False
                print("Displaying continue!")
    elif command_key == 'q':
        print("Display ended!")
        cv.destroyAllWindows()
        sys.exit()
    else:
        continue

 


版权声明:本文为qq_41074679原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。