You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Racket GUI Toolkit 中如何正确嵌入可跳转的超链接

Racket GUI 嵌入可点击超链接的实现方案

原生的message%控件本身不支持点击事件绑定,也没有超链接跳转的内置逻辑,需要通过自定义控件+调用系统打开链接的接口实现,具体方案如下:

前置依赖

需要先导入net/sendurl模块,该模块提供的send-url函数可以直接调用系统默认浏览器打开指定链接:

(require net/sendurl
         racket/gui)

完整实现代码

;; 定义自定义超链接控件类
(define hyperlink%
  (class message%
    (init-field [url ""] ; 超链接指向的目标地址
                [hover-color "blue"] ; 默认字体颜色
                [normal-color "purple"]) ; 点击后的字体颜色,可自定义
    (super-new)
    ;; 初始化样式:蓝色、下划线
    (send this set-color hover-color)
    (send this set-font (send the-font-list find-or-create-font
                              12 'default 'normal 'normal #t)) ; 最后一个参数#t代表下划线
    ;; 处理鼠标事件
    (define/override (on-event e)
      (cond
        ;; 左键点击时打开链接
        [(send e button-down? 'left)
         (send-url url)
         (send this set-color normal-color)]
        ;; 鼠标悬浮时切换为手型指针
        [(send e entering?)
         (send (send this get-parent) set-cursor (make-object cursor% 'hand))]
        ;; 鼠标离开时切回默认指针
        [(send e leaving?)
         (send (send this get-parent) set-cursor #f)]))
    ))

;; 原代码中的frame定义
(define my-frame (new frame% [parent #f] [label "test"] [width 300] [height 100]))

;; 替换原来的message%为自定义的hyperlink%
(new hyperlink%
     [parent my-frame]
     [label "https://www.google.com"]
     [url "https://www.google.com"])

(send my-frame show #t)

实现说明

  • 自定义的hyperlink%继承自原生message%,保留了文本显示的所有原有特性,额外新增了超链接相关的交互逻辑
  • 点击事件触发时通过send-url调用系统默认浏览器打开链接,无需自己处理跨平台的浏览器启动逻辑
  • 内置了超链接常见的样式效果:蓝色字体、下划线、点击后变色、鼠标悬浮显示手型,符合普通用户的超链接使用习惯

内容的提问来源于stack exchange,提问作者TomatoFarmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 21:39:03