在显示窗口之前关闭的简单ocaml图形程序 [英] simple ocaml graphics progam that close before its window is displayed

查看:130
本文介绍了在显示窗口之前关闭的简单ocaml图形程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的系统是ArchLinux

My system is ArchLinux

我有一个简单的ocaml程序,该程序应该创建一个窗口并使用绘图基元.

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

我可以编译它:

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.

推荐答案

这里的问题是您的程序执行一系列命令,完成后便退出.当它退出时,它关闭与其关联的窗口.如果希望窗口保持打开状态,则需要防止该程序退出.

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.

一种可能的解决方案是使用Unixsleep将窗口保持打开状态,例如5秒,方法是在程序末尾添加Unix.sleep 5并使用以下命令对其进行编译:

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 

另一种选择是通过在最后一个fill_rect之后插入一个调用loop ()来简单地进入无限循环. loop的定义如下:

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

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

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

这篇关于在显示窗口之前关闭的简单ocaml图形程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆