simple ocaml graphics progam that close before its window is displayed

て烟熏妆下的殇ゞ 提交于 2019-12-12 14:44:05

问题


My system is ArchLinux

I have this simple ocaml program that should create a window and use drawing primitives.

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

I can compile it:

ocamlc graphics.cma -o graphics_exple graphics_exple.ml 

And launch it with:

./graphics_exple

I see in my taskbar that a new window take focus then disapear without seing any window.


回答1:


The problem here is that your program executes a sequence of commands and once it's done, it exits. And when it exits, it closes the window associated to it. If you want the window to stay open, you need to prevent the program from exiting.

One possible solution is to use Unix's sleep to keep the window open for, say, 5 seconds by adding Unix.sleep 5 at the end of your program and compiling it with the command:

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

Another alternative is to simply enter an infinite loop by inserting a call loop () after your last fill_rect. Where loop is defined like so:

let rec loop () = loop ()

Finally, you can have a handler waiting for inputs from the user and acting on them. For sake of the argument, say that you want to print in the console all the characters typed by the user except for 'q' which makes the program exit. You only need to insert interactive () at the end of your script where interactive is defined as:

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 ()



回答2:


All desktop graphics like Tcl/Tk or GTK have an event loop that must be entered to give the system time to execute and display.

You could use

Thread.delay 10.0

or the like.

I recommend compiling with ocamlfind like this, with graphtemp.ml being your test file:

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


来源:https://stackoverflow.com/questions/36263152/simple-ocaml-graphics-progam-that-close-before-its-window-is-displayed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!