在显示 window 之前关闭的简单 ocaml 图形程序

simple ocaml graphics progam that close before its window is displayed

我的系统是 ArchLinux

我有这个简单的 ocaml 程序,它应该创建 window 并使用绘图基元。

open Graphics

let _ =
  open_graph "";
  set_window_title "Graphics example";
  draw_rect 50 50 300 200;
  set_color red;
  fill_rect 50 50 300 200;
  set_color blue;
  draw_rect 100 100 200 100;
  fill_rect 100 100 200 100

我可以编译它:

ocamlc graphics.cma -o graphics_exple graphics_exple.ml 

并启动它:

./graphics_exple

我在我的任务栏中看到一个新的 window 获得焦点然后消失而没有看到任何 window。

这里的问题是您的程序执行一系列命令,一旦完成,它就会退出。当它退出时,它会关闭与之关联的 window。如果您希望 window 保持打开状态,您需要阻止程序退出。

一个可能的解决方案是使用 Unixsleep 来保持 window 打开,比如说 5 秒,方法是在程序结束并使用命令编译它:

ocamlc graphics.cma unix.cma -o graphics_exple graphics_exple.ml 

另一种方法是在最后一个 fill_rect 之后插入一个调用 loop (),从而进入无限循环。 loop 的定义如下:

let rec loop () = loop ()

最后,您可以让处理程序等待用户的输入并对其进行操作。为了论证,假设您想在控制台中打印用户键入的所有字符,但 'q' 除外,这会使程序退出。您只需要在脚本末尾插入 interactive (),其中 interactive 定义为:

let rec interactive () =
  let event = wait_next_event [Key_pressed] in
  if event.key == 'q' then exit 0
  else print_char event.key; print_newline (); interactive ()

所有桌面图形,如 Tcl/Tk 或 GTK 都有一个事件循环,必须进入事件循环才能让系统有时间执行和显示。

你可以使用

Thread.delay 10.0

之类的。

我建议像这样使用 ocamlfind 进行编译,graphtemp.ml 作为您的测试文件:

ocamlfind ocamlc -o graphtemp -thread -package graphics -linkpkg graphtemp.ml