Tcl/tk - 如何使线程中的 yesno messageBox 可见
Tcl/tk - how to make yesno messageBox in thread visible
我创建了一个简单的线程来持续显示消息框,直到用户不想进行某些操作为止。以下是代码:
thread::create { while [tk_messageBox -message "Do you want to Exit?!!" -type yesno] {
doSomething
}}
但是虽然创建了线程,但是没有显示消息框。
我怎样才能真正看到这些消息框?
您还需要让 Tk 出现在线程中;默认情况下,从属线程中仅存在 Thread 包:
thread::create {
package require Tk
while [tk_messageBox -message "Do you want to Exit?!!" -type yesno] {
doSomething
}
}
此外,您还需要修复代码中的许多其他问题。
- 总是把
while
的条件放在{
大括号}
中。如果没有它,表达式的动态部分将只被评估一次,这真的不是你想要的 while
.
- 确保您的线程执行
thread::wait
,因为这样可以改进进程和线程管理。您的消息框循环需要完全重写。
这可能会导致此代码:
thread::create {
package require Tk
proc periodicallyMaybeDoSomething {} {
if {[tk_messageBox -message "Do you want to Exit?!!" -type yesno]} {
thread::exit
}
doSomething
# pick a better delay maybe?
after 1 periodicallyMaybeDoSomething
}
after 1 periodicallyMaybeDoSomething
thread::wait
}
如果您使用的是 8.6,则可以使用协程来使代码更优雅。
我创建了一个简单的线程来持续显示消息框,直到用户不想进行某些操作为止。以下是代码:
thread::create { while [tk_messageBox -message "Do you want to Exit?!!" -type yesno] {
doSomething
}}
但是虽然创建了线程,但是没有显示消息框。 我怎样才能真正看到这些消息框?
您还需要让 Tk 出现在线程中;默认情况下,从属线程中仅存在 Thread 包:
thread::create {
package require Tk
while [tk_messageBox -message "Do you want to Exit?!!" -type yesno] {
doSomething
}
}
此外,您还需要修复代码中的许多其他问题。
- 总是把
while
的条件放在{
大括号}
中。如果没有它,表达式的动态部分将只被评估一次,这真的不是你想要的while
. - 确保您的线程执行
thread::wait
,因为这样可以改进进程和线程管理。您的消息框循环需要完全重写。
这可能会导致此代码:
thread::create {
package require Tk
proc periodicallyMaybeDoSomething {} {
if {[tk_messageBox -message "Do you want to Exit?!!" -type yesno]} {
thread::exit
}
doSomething
# pick a better delay maybe?
after 1 periodicallyMaybeDoSomething
}
after 1 periodicallyMaybeDoSomething
thread::wait
}
如果您使用的是 8.6,则可以使用协程来使代码更优雅。