0

我正在尝试来自 HtDP 的练习 22.3.3,但不知道如何检索被单击按钮的标签。我收到这条消息draw-message: expected <string> as second argument, given: (instantiate (class ...) ...),似乎表明我需要一个字符串,但我得到了一个类的实例。回调中有答案吗?如果是这样,我该如何解构它?


这是我到目前为止所拥有的:

(define pad1
  '((1 2 3)
    (4 5 6)
    (7 8 9)
    (\# 0 *)))

(define pad2 
  '((1 2 3  +)
    (4 5 6  -)
    (7 8 9  *)
    (0 = \. /)))

(define (title t)
  (make-message t))

(define display
  (make-message ""))

(define (pad->gui p)
  (cond
    [(empty? p) empty]
    [else (cons (button-maker (first p))
                (pad->gui (rest p)))]))

;; make buttons out of a list
(define (button-maker a-list)
  (cond
    [(empty? a-list) empty]
    [(number? (first a-list))(cons (make-button (number->string (first a-list)) call-back)
                                   (button-maker (rest a-list)))]
    [(symbol? (first a-list))(cons (make-button (symbol->string (first a-list)) call-back)
                                   (button-maker (rest a-list)))]))

(define (call-back b)
  (draw-message display ...))


(create-window
 (append (list (list (title "Virtual Phone")))
         (list (list display))
         (pad->gui pad1)))

如果我理解正确,每个按钮都会call-back在按下时调用。这反过来应该调用display它将更新文本。但是,我不明白如何检索调用者的标签。例如,如果按下按钮“9”,它将调用call-back. 但是如何检索值“9”?这是我不确定的。

4

1 回答 1

3

正确的。draw-message 函数使用一个“窗口”和一个“字符串”,这在同一部分的图 62 中进行了说明。您似乎将其应用于“按钮对象”。另请参阅同一部分中的示例 2,如下所示:

(define a-text-field
  (make-text "Enter Text:"))

(define a-message
  (make-message "`Hello World' is a silly program."))

(define (echo-message e)
  (draw-message a-message (text-contents a-text-field)))

(define w (create-window
           (list (list a-text-field a-message)
                 (list (make-button "Copy Now" echo-message)))))

当您单击“立即复制”按钮时,查看 echo-message 如何更改显示。

提示:由于每个按钮都有一个回调,因此您确切地知道从哪个按钮回调将哪个字符串发送到显示器。

更正:书中的示例1已损坏。利用

 (define u
  (create-window (list (list (make-button "Close" (lambda (x) (hide-window u)))))))

反而。

于 2011-01-06T14:39:18.710 回答