溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python如何實(shí)現(xiàn)錄屏功能

發(fā)布時(shí)間:2023-03-24 10:50:06 來源:億速云 閱讀:79 作者:iii 欄目:開發(fā)技術(shù)

這篇“Python如何實(shí)現(xiàn)錄屏功能”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Python如何實(shí)現(xiàn)錄屏功能”文章吧。

    一、界面開發(fā)

        #設(shè)置主界面
    def set_init_window(self):
        # 去掉tkinter默認(rèn)的標(biāo)題
        self.tk.title('')
        # 隱藏默認(rèn)圖標(biāo)
        self.tk.iconbitmap(self.icon_path())
        #獲取屏幕的寬度
        screeWidth = self.tk.winfo_screenwidth()
        #獲取屏幕高度
        screeHeight = self.tk.winfo_screenheight()
        
        width = int((screeWidth - 500) / 2)
        height = int((screeHeight - 300) / 2)
        # 設(shè)置主界面的大小和默認(rèn)位置
        self.tk.geometry(f'500x100+{width}+{height}')
        
        #添加開始錄制按鈕,點(diǎn)擊之后開啟兩個(gè)線程:一個(gè)錄屏、一個(gè)監(jiān)聽鍵盤
        btn1 = tkinter.Button(self.tk, width=5, height=1, text='開始',
        command=lambda:[threading.Thread(target=self.video_record).start(),threading.Thread(target=self.start_listen).start()])
        btn1.pack()
        # 設(shè)置按鈕位置
        btn1.place(x=110, y=50, anchor='n')
        
        #開啟新線程設(shè)置錄屏范圍
        btn2 = tkinter.Button(self.tk, width=15, height=1, text='設(shè)置錄制區(qū)域', command=lambda:threading.Thread(target=self.set_range).start())
        btn2.pack()
        btn2.place(x=230, y=50, anchor='n')
    
    
    #生成透明的icon圖標(biāo)
    def icon_path(self):
        ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
                b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00'
                b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
                b'\x00\x01\x00\x00\x00\x01') + b'\x00' * 1282 + b'\xff' * 64
        _, ICON_PATH = tempfile.mkstemp()
        with open(ICON_PATH, 'wb') as icon_file:
            icon_file.write(ICON)
        return ICON_PATH

    二、錄屏參數(shù)設(shè)置

    1.設(shè)置錄屏范圍

    #設(shè)置錄屏范圍
    def set_range(self):
        #self.init_window.withdraw() #隱藏窗口
        self.tk.state('icon')#窗口最小化
        screeWidth = self.tk.winfo_screenwidth()
        screeHeight = self.tk.winfo_screenheight()
    
        self.newFrame = tkinter.Toplevel(self.tk,width=screeWidth,height=screeHeight,bg='white')#開啟新窗口
        self.newFrame.attributes('-transparentcolor', 'white')  # 使白色為透明色
        self.newFrame.overrideredirect(True)  # 隱藏導(dǎo)航欄
    
        self.canvas = tkinter.Canvas(self.newFrame,bg='white',bd=0,width=screeWidth,height=screeHeight)
        self.canvas.bind('<Button-1>', self.onLeftButtonDown)#按下左鍵
        self.canvas.bind('<B1-Motion>', self.onLeftButtonMove)#移動(dòng)鼠標(biāo)
        self.canvas.bind('<ButtonRelease-1>', self.onLeftButtonUp)#抬起左鍵
        self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)
    
        time.sleep(0.3)
        im = ImageGrab.grab()
        # 暫存全屏截圖
        im.save('temp.png')
        im.close()
        self.image = tkinter.PhotoImage(file='temp.png')
        os.remove('temp.png')
        self.canvas.create_image(screeWidth//2, screeHeight//2, image=self.image)

    2.鼠標(biāo)事件監(jiān)聽

    #按下鼠標(biāo)
    def onLeftButtonDown(self,event):
        try:
            self.canvas.delete(self.lastDraw)
            self.canvas.delete(self.dot1)
            self.canvas.delete(self.dot2)
            self.btn3.destroy()
        except Exception as e:
            pass
    
        self.X = event.x
        self.Y = event.y
        self.X2 = 0
        self.Y2 = 0
    
    #移動(dòng)鼠標(biāo)
    def onLeftButtonMove(self,event):
        try:  # 刪除剛畫完的圖形,不然所有畫的框都會(huì)出現(xiàn)
            self.canvas.delete(self.lastDraw)
            self.canvas.delete(self.dot1)
            self.canvas.delete(self.dot2)
            self.btn3.destroy()
        except Exception as e:
            pass
    
        self.X2 = event.x
        self.Y2 = event.y
        self.lastDraw = self.canvas.create_rectangle(self.X, self.Y, event.x, event.y,width=2, outline='pink')
    
    #松開鼠標(biāo)
    def onLeftButtonUp(self,event):
        print("起點(diǎn)", self.X, self.Y)
        print("終點(diǎn)", self.X2, self.Y2)
    
        if self.X2==0 and self.X2==0:
            return
    
        self.width, self.high = self.X2-self.X,self.Y2-self.Y
        self.region = (self.X, self.Y, self.X2, self.Y2)
    
        self.dot1=self.canvas.create_text(self.X, self.Y - 10, text=f'({self.X},{self.Y})', font=("Purisa", 12), fill="pink")
        self.dot2=self.canvas.create_text(self.X2, self.Y2 + 10, text=f'({self.X2},{self.Y2})', font=("Purisa", 12), fill="pink")
    
        # self.newFrame.destroy()#銷毀窗口
        # self.init_window.deiconify()#顯示窗口
        # self.tk.state('normal')  # 取消窗口最小化
    
        self.btn3 = tkinter.Button(self.canvas, width=15, height=1, text='確定錄制區(qū)域',bg='pink',fg='#64854c',command=lambda:[self.newFrame.destroy(),self.tk.state('normal')])
        self.btn3.pack()
        self.btn3.place(x=self.X2-20, y=self.Y2+20, anchor='n')

    3.鍵盤事件監(jiān)聽

    # 開始監(jiān)聽
    def start_listen(self):
        with keyboard.Listener(on_press=self.on_press) as listener:
            listener.join()
        # 監(jiān)聽按鍵
    def on_press(self,key):
        if key == keyboard.Key.esc:
            self.flag = True  # 改變
            return False  # 返回False,鍵盤監(jiān)聽結(jié)束!

    三、錄屏操作

    def video_record(self):
         fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
         out = cv2.VideoWriter('output.mp4', fourcc, 14, (self.width, self.high))  # 參數(shù)分別為 輸出文件名,解碼方式,幀數(shù),錄像范圍
         self.count = 1
         while (True):
             img = ImageGrab.grab(self.region) #指定截取坐標(biāo)(左邊X,上邊Y,右邊X,下邊Y)
             img_np = numpy.array(img)
             frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)  # ImageGrab獲取的顏色為BGR排序,需轉(zhuǎn)換為RGB
             out.write(frame)
             self.count += 1
             label = tkinter.Label(self.tk, text=f"{int(self.count / 14)}秒")
             label.pack()
             label.place(x=320, y=55, anchor='n')
             # 點(diǎn)擊ESC退出
             if self.flag == True:
                 tkinter.messagebox.showinfo('提示', '錄屏結(jié)束')
                 self.flag = False  # 改變錄屏狀態(tài)
                 break
         out.release()
         cv2.destroyAllWindows()

    以上就是關(guān)于“Python如何實(shí)現(xiàn)錄屏功能”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI