user-interface - Tcl/Tk 示例?

标签 user-interface scripting tcl tk

Tcl/Tk是一种编写小型 GUI 脚本的简单方法。

任何人都可以用一个按钮和一个文本小部件举一个很好的例子。当按下按钮时,应该执行一个 shell 命令并将输出通过管道传输到文本小部件。

如果你有其他有用的任务的漂亮和干净的例子,请也添加它们。

最佳答案

这是一个使用 fileevents 的更完整示例。这将一直自动滚动。出于可用性目的,您可能只想在文本底部可见时自动滚动(即:如果用户没有移动滚动条),但我会将其作为练习留给读者,以保留这个已经很长的示例从不再。

package require Tk

proc main {} {
    if {[lsearch -exact [font names] TkDefaultFont] == -1} {
        # older versions of Tk don't define this font, so pick something
        # suitable
        font create TkDefaultFont -family Helvetica -size 12
    }
    # in 8.5 we can use {*} but this will work in earlier versions
    eval font create TkBoldFont [font actual TkDefaultFont] -weight bold

    buildUI
}

proc buildUI {} {
    frame .toolbar
    scrollbar .vsb -command [list .t yview]
    text .t \
        -width 80 -height 20 \
        -yscrollcommand [list .vsb set] \
        -highlightthickness 0
    .t tag configure command -font TkBoldFont
    .t tag configure error   -font TkDefaultFont -foreground firebrick
    .t tag configure output  -font TkDefaultFont -foreground black

    grid .toolbar -sticky nsew
    grid .t .vsb  -sticky nsew
    grid rowconfigure . 1 -weight 1
    grid columnconfigure . 0 -weight 1

    set i 0
    foreach {label command} {
        date     {date} 
        uptime   {uptime} 
        ls       {ls -l}
    } {
        button .b$i -text $label -command [list runCommand $command]
        pack .b$i -in .toolbar -side left
        incr i
    }
}

proc output {type text} {
    .t configure -state normal
    .t insert end $text $type "\n"
    .t see end
    .t configure -state disabled
}

proc runCommand {cmd} {
    output command $cmd
    set f [open "| $cmd" r]
    fconfigure $f -blocking false
    fileevent $f readable  [list handleFileEvent $f]
}

proc closePipe {f} {
    # turn blocking on so we can catch any errors
    fconfigure $f -blocking true
    if {[catch {close $f} err]} {
        output error $err
    }
}

proc handleFileEvent {f} {
    set status [catch { gets $f line } result]
    if { $status != 0 } {
        # unexpected error
        output error $result
        closePipe $f

    } elseif { $result >= 0 } {
        # we got some output
        output normal $line

    } elseif { [eof $f] } {
        # End of file
        closePipe $f

    } elseif { [fblocked $f] } {
        # Read blocked, so do nothing
    }
}


main

关于user-interface - Tcl/Tk 示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/166231/

相关文章:

ssh - 网络中断后自动(或更容易)重新连接到 screen session

powershell - 导出到excel的脚本

java - 如何在 boxLayout 的两个按钮之间添加空格?

Java GUI 未加载

android - 理解 View.setTranslationY() [/X() ]

bash - 无法使用期望语句将数据添加到文件 Tcl

shell - 如何使用参数在 tchsh 中执行 tcl 脚本

python - 模块之间的 wxPython、Threads 和 PostEvent

javascript - 如何在 InDesign 文档中查找所有对象样式覆盖

data-structures - 如何在 Tcl 中创建数据结构?