Re: Control placement of a button within a text widget



Helmut Giese wrote:
> Hello out there,
> I want to embed a button within a text widget - this is easy. However,
> I also want it to be centered in the middle - this is hard (ok, hard
> for me).
> Here is what I have so far:
> ---
> package require Tk
> # just for re-sourcing this file
> foreach w [pack slaves .] {destroy $w}
>
> pack [text .t -width 12] -fill x
> set s "This is line 1.
> This is line 2.
> This is line 3.
> "
> .t insert end $s
> # this line helps a bit
> #.t insert end " "
> # now the button
> .t window create end -align center -create \
> [list button .t.btn -text Ok \
> -command {puts "Click"}]
> ---
> The button will appear flush left. I thought that '-align center'
> would be the option I need, but this appears to not be the case.
>
> If I uncomment the line marked by "# this line helps a bit" the button
> will be pushed over to the right. I could experiment how many spaces
> to fill in to have the button in the middle, but this is a kludge:
> - If the text window is made wider, the button will stay at its place
> and won't be centered any more.
> - If the user changes the font, the button is likely to not be
> centered any more.
>
> Tcl (and Tk) being what it is, I am sure that there is a solution for
> what I want. Any hints in this direction will be greatly appreciated.
> Best regards
> Helmut Giese

You can with some trickery. Just create the window on a line that is
center justified (align refers to 'vertical' alignment). Sort of like:

This is line 1
This is line 2
This is line 3
blah[OK button]blah

if you make the text on that line space bars, then you have what you
want:

pack [text .t -width 12] -fill x
..t tag configure ctr -justify center
set s "This is line 1.
This is line 2.
This is line 3.
"
..t insert end $s
# this line helps a bit
#.t insert end " "
# now the button
..t insert end " " ctr
..t window create end -align center -create \
[list button .t.btn -text Ok \
-command {puts "Click"}]
..t insert end " " ctr
..t insert end "\n"

# Note how I surround the button with space bars to maintain
# correct center.

.


Quantcast