2017-11-17 141 views
1

因此,我正在編寫一個小的Racket應用程序,該應用程序將解析(格式非常差的).txt文件並輸出可在Excel中使用的.csv。我想要做的第一件事是打開一個帶有一個按鈕的小窗口,該按鈕打開一個文件對話框,以便用戶可以選擇要轉換的文件(就像任何啓動打開的文件選擇對話框的程序一樣)。我在網上查了一下,找不到任何東西。這將是一個本地應用程序,所以我在POST服務器上找到的東西並不相關。你怎麼能在球拍上做到這一點?如何在球拍中創建文件上傳按鈕?

回答

0

程序get-fileput-file存在於#lang racket/gui中。兩者都可以用來通過對話框從用戶獲取文件路徑名。 get-file是針對選擇現有文件而設計的,而put-file則針對創建新文件。

考慮下面的例子,執行以下操作:

  • 它創建包含「選擇文件」按鈕的窗口。
  • 單擊按鈕時,會出現一個對話框來選擇文件(可以是用於轉換的.txt文件)。
  • 一旦選擇了文本文件,它將打開另一個對話框來選擇一個文件來保存轉換後的數據(可以是.csv文件)。

#lang racket/gui 

;; Prints file's contents line by line 
(define (print-each-line input-file) 
    (define line (read-line input-file)) 
    (unless (eof-object? line) 
    ;; 'line' here represents a line of txt file's contents 
    ;; The line can be processed/modified to any desired output, but 
    ;; for the purposes of this example, the line will simply be 
    ;; printed the way it is without any "processing". 
    (println line) 
    (print-each-line input-file))) 

;; Convert txt to csv by printing each line of txt 
;; to the csv file using print-each-line (above) 
(define (convert txt csv) 
    (define in (open-input-file txt)) 
    (with-output-to-file csv 
    (lambda() (print-each-line in))) 
    (close-input-port in)) 

;; Make a frame by instantiating the frame% class 
(define frame (new frame% [label "Example"])) 

;; Make a button in the frame 
(new button% [parent frame] 
      [label "Select File"] 
      ;; Callback procedure for a button click: 
      [callback 
       (lambda (button event) 
       (define txt (get-file)) 
       (define csv (put-file)) 
       (convert txt csv))]) 

;; Show the frame by calling its show method 
(send frame show #t) 
+0

太感謝你了!這正是我需要了解它如何工作的。我現在閱讀更多關於框架的內容。感謝您的幫助 – matzy

+0

不客氣:) – assefamaru

0

目前尚不清楚您需要什麼。如果您想知道如何使用文件,請參見File ports部分,但如果您需要知道如何創建和使用GUI對象,請參見Windowing。基於GTK構建GUI應用程序(在球拍實現中使用)對於新用戶來說這不是一件容易的事情。這不是我的生意,但我認爲如果你拿一些RAD(比如Lazarus用於對象pascal,MS Visual Studio for C#),那麼比沒有經驗的編寫GUI文本更快更容易。