import
mss
import
mss.tools
import
cv2
import
numpy as np
import
tkinter as tk
from
tkinter
import
messagebox, filedialog
import
os
with mss.mss() as sct:
screen_size
=
(sct.monitors[
1
][
'width'
], sct.monitors[
1
][
'height'
])
fourcc
=
cv2.VideoWriter_fourcc(
*
'mp4v'
)
recording
=
False
frames
=
[]
output_writer
=
None
def
start_recording():
global
recording, start_button_text
if
not
recording:
recording
=
True
start_button_text.
set
(
"录制中"
)
record_screen()
def
stop_recording():
global
recording, frames, output_writer, start_button_text
if
recording:
recording
=
False
start_button_text.
set
(
"开始录制"
)
try
:
output_file
=
filedialog.asksaveasfilename(defaultextension
=
".mp4"
, filetypes
=
[(
"MP4 files"
,
"*.mp4"
)])
if
not
output_file:
return
if
os.path.exists(output_file):
choice
=
messagebox.askyesnocancel(
"文件已存在"
,
f
"文件 {output_file} 已存在,是否覆盖?"
)
if
choice
is
None
:
return
elif
choice
=
=
False
:
return
output_writer
=
cv2.VideoWriter(output_file, fourcc,
20.0
, screen_size)
for
frame
in
frames:
output_writer.write(frame)
output_writer.release()
frames.clear()
messagebox.showinfo(
"停止"
,
"已停止录制并保存文件。"
)
except
Exception as e:
messagebox.showerror(
"错误"
,
str
(e))
finally
:
output_writer
=
None
def
record_screen():
if
recording:
with mss.mss() as sct:
monitor
=
{
'top'
:
0
,
'left'
:
0
,
'width'
: screen_size[
0
],
'height'
: screen_size[
1
]}
img
=
sct.grab(monitor)
frame
=
np.array(img)
frame
=
cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
frames.append(frame)
root.after(
15
, record_screen)
root
=
tk.Tk()
root.title(
"屏幕录制小工具 by.KOG丛林"
)
frame
=
tk.Frame(root)
frame.pack()
start_button_text
=
tk.StringVar(value
=
"开始录制 "
)
start_button
=
tk.Button(frame, textvariable
=
start_button_text, command
=
start_recording)
start_button.pack(side
=
tk.LEFT)
stop_button
=
tk.Button(frame, text
=
" 停止录制"
, command
=
stop_recording)
stop_button.pack(side
=
tk.LEFT)
root.mainloop()