【问题标题】:TCL/TK create and destroy widget with checkbuttonTCL/TK 使用复选按钮创建和销毁小部件
【发布时间】:2020-07-16 08:41:00
【问题描述】:

我想创建和销毁一个带有复选按钮的小部件。小部件将在检查按钮被选中时创建,并在取消选中检查按钮时被销毁。创建工作正常,但是当小部件应该被销毁时,将显示错误消息Error: window name "ser" already exists in parent

package require Tk

wm title . "Some Test"
grid[ttk::frame .c -padding "3 3 12 12"] -column 0 -row 0 -sticky nwes
grid columnconfigure . 0 -weight 1; grid rowconfigure . 0 -weight 1
grid [ttk::checkbutton .c.checkSer -command createWidget \ 
    -variable CB -onvalue 1 -offvalue 0] -column 1 -row 3 -sticky w
    
set CB 0

proc createWidget {} {
    if {[catch {info exists $::ser} fid]} {
        grid [ttk::entry .c.ser -width 12 -textvariable ser] -column 2 -row 2 -sticky we
        grid [ttk::label .c.serlbl -text "Ser"] -column 1 -row 2 -sticky w
    } else {
        destroy .c.ser .c.serlbl
    }
}

如何在没有此错误的情况下销毁小部件?

【问题讨论】:

    标签: tcl tk


    【解决方案1】:

    问题是你的声明info exists $::ser。这会尝试读取全局变量 ser,然后检查是否存在具有存储在该变量中的名称的变量。

    所以您可能打算使用info exists ::ser(不带$)。但这也不会像你想要的那样工作。 ttk::entry 小部件在用户在条目中键入内容之前实际上并没有创建它的文本变量,并且在小部件被销毁时该变量不会被删除。

    您将需要不同的方法来确定是创建还是销毁小部件。例如:

    if {![winfo exists .c.ser]} {
        # Create the widgets
    } else {
        # Destroy the widgets
    }
    

    【讨论】:

    • 谢谢,这对我有很大帮助。我是 TCL 的新手。
    • winfo exists 命令是测试是否存在具有特定名称的小部件的规范方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多