【发布时间】:2019-03-15 14:20:00
【问题描述】:
我正在尝试使用 tcl/tk 画布实用程序在文件中绘制实时更改。我编写了一个简单的代码来查找文件中的差异并使用.c create line $oldx $oldy $newx $newy 命令绘制它。
我的代码有一个 while 循环来不断检查文件中的更改。当我注释掉 while 循环时,绘图画布可以正常打开,但是当我取消注释 while 循环时,绘图画布根本不会打开。
请提出修改建议,代码:
#!/usr/bin/wish
#PROGRAM 2 : Print something when a file is changed
#
#package require Tk
#graph prep
set width 100
set height 100
canvas .c -width $width -height $height -background white
pack .c
#bind .c <Configure> {
# bind .c <Configure> {}
# .c xview scroll 0 unit
# set t 0
#}
#set t 0
#.c create line $t 239 [expr $t + 5] 239 -fill gray
.c create line 0 12 1 13
#Initial reading
set filename "data.txt"
#puts $filename
if [file exists $filename] {
#puts "file exits!"
set accessTime [file mtime $filename]
#puts $accessTime
}
#opening file
set a [open $filename]
set lines [split [read -nonewline $a] "\n"]
close $a; # Saves a few bytes :-)
#puts [llength $lines]
#printing file
set oldx 0
set oldy [lindex $lines 0]
for {set i 1} {$i < [llength $lines]} {incr i} {
#puts "$i : [lindex $lines $i]"
set newx $i
set newy [lindex $lines $i]
.c create line $oldx $oldy $newx $newy
set oldx $newx
set oldy $newy
}
## after 10000
## #looping to detect change
while 1 {
if [file exists $filename] {
after 1000
# check if new access time
set nAccessTime [file mtime $filename]
if {$accessTime != $nAccessTime} {
#puts $nAccessTime
#puts "found new"
#update access time
set accessTime $nAccessTime
#read new lines
set a [open $filename]
set lines [split [read -nonewline $a] "\n"]
close $a; # Saves a few bytes :-)
#puts [llength $lines]
for {} {$i < [llength $lines]} {incr i} {
#puts "$i : [lindex $lines $i]"
set newx $i
set newy [lindex $lines $i]
.c create line $oldx $oldy $newx $newy
set oldx $newx
set oldy $newy
}
}
}
}
【问题讨论】:
-
我可能是错的,但我相信它与事件处理程序有关,或者我认为它的名字是。基本上,tk 元素仅在没有待处理的任务要做之后才绘制,并且在您的情况下,总是有 something 要做(包括在循环之间等待)。我宁愿将整个部分放在
proc中的 while 循环中并调用一次 proc,并在 proc 结束时使用after 1000 procname创建循环。 -
@Jerry 更容易使用 Tcl 8.6 协程。容易得多。