您不能将一个小部件或一组小部件移动到新的父级,但您可以使用一些简单的例程来模拟它。我不在 python 中工作,但您应该能够将以下代码从 tcl 转换为 tkinter。通过模拟,我的意思是您将小部件和任何孩子递归地复制到新的父级。Tk 提供了精确复制要移动/复制的小部件的布局、绑定和外观所需的内省,包括所有子小部件。下面的例程将允许您将单个或复杂的小部件移动或复制到新的父级。
proc getWidgetType { w } {
set class [winfo class $w ]
if { [ string index $class 0 ] eq "T" &&
[ string match "\[A-Z\]" [string index $class 1 ] ] } {
set class [string range [string tolower $class ] 1 end ]
set class "ttk::$class"
} else {
set class [string tolower $class ]
}
return $class
}
proc getConfigOptions { w } {
set configure [ $w configure ]
set options {}
foreach f $configure {
if { [llength $f ] < 3 } { continue; }
set name [ lindex $f 0 ]
set default [ lindex $f end-1 ]
set value [ lindex $f end ]
if { $default ne $value } {
lappend options $name $value
}
}
return $options
}
proc copyWidget { w newparent { level 0 } } {
set type [ getWidgetType $w ]
set name [ string trimright $newparent.[lindex [split $w "." ] end ] "." ]
set retval [ $type $name {*}[ getConfigOptions $w ] ]
foreach b [ bind $w ] {
puts "bind $retval $b [subst { [bind $w $b ] } ] "
catch { bind $retval $b [subst { [bind $w $b ] } ] }
}
if { $level > 0 } {
if { [ catch { pack info $w } err ] == 0 } {
array set temp [ pack info $w ]
array unset temp -in
catch { pack $name {*}[array get temp ] }
} elseif { [ catch { grid info $w } err ] == 0 } {
array set temp [ grid info $w ]
array unset temp -in
catch { grid $name {*}[array get temp ] }
}
}
incr level
if { [ pack slaves $w ] ne "" } {
foreach f [ pack slaves $w ] {
copyWidget $f $name $level
}
} else {
foreach f [winfo children $w ] {
copyWidget $f $name $level
}
}
return $retval
}
proc moveWidget { w newparent } {
set retval [ copyWidget $w $newparent ]
destroy $w
return $retval
}
# assume we have already created a toplevel with complex layout named
# .input with subframe .input.frame.tframe that we want to transfer to
# a new toplevel .x . There is a cancel button we want to transfer
# also at .input.frame.bframe.icancel and we will grid it into
# .x.tframe .
toplevel .x
set form [ moveWidget .input.frame.tframe .x ]
set cancel [ moveWidget .input.frame.bframe.icancel .x.tframe ]
grid $cancel -row 2 -column 2 -sticky new
pack $form -anchor center -expand 1 -fill both -side top