[Tkinter-discuss] Learning Python/Tkinter and struggling with the text object

Michael Lange klappnase at web.de
Fri Dec 9 10:55:31 EST 2016


Hi,

On Thu, 8 Dec 2016 11:00:50 -0700
"Alan L Dickman" <adickman at us.ibm.com> wrote:

> Thanks in advance for any help! I'm just learning Python and Tkinter.
> Can anyone suggest why this program does not insert 'some text' into
> text box t1 when the start button is clicked? No errors are thrown when
> I run the program in PyCharm
> 
> from tkinter import *
> 
> class Window(Frame):
>     t1 = []
>     def __init__(self, master=None)
>         Frame.__init__(self, master)
>         self.master = master
>         self.master.title("My Title")
>         StartButton = Button(self, text="Start", command=self.start, bg=
> '#006ba6', fg="white")
>         StartButton.grid(row=0, columnspan=3, sticky=(N, S, W, E))
>         Label(self, text="Your Name").grid(row=1, sticky=(N, S, W, E))
>         t1 = Text(self, height=2)
>         t1.grid(row=1, column=1, sticky=(N, S, W, E))
>         self.t1.insert( 0, 'some text')
>         quitButton = Button(self, text="Quit",
> command=self.client_quit, bg='#006ba6', fg="white")
>         quitButton.grid(row=5, columnspan=3, sticky=(N, S, W, E))
>         self.grid(sticky=(N, S, W, E))
> 
>     def start(self):
>         self.t1.insert(0, 'some text')
(...)

there are various problems here:
You do  self.t1.insert( 0, 'some text') , your text widget however is
"t1", self.t1 is an empty list, so your list after the button press will
look like ['some text', 'some text'] .
Next, if you try to insert a string into a text widget, you need to
specify the index with a construct like "line.character", so if you want
to insert something at the start of the first line, use 1.0 instead of 0,
otherwise a TclError will be thrown, as in:

>>> text.insert(0, 'foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "Tkinter.py", line 3236, in insert
    self.tk.call((self._w, 'insert', index, chars) + args)
_tkinter.TclError: bad text index "0"

Best regards

Michael


.-.. .. ...- .   .-.. --- -. --.   .- -. -..   .--. .-. --- ... .--. . .-.

Immortality consists largely of boredom.
		-- Zefrem Cochrane, "Metamorphosis", stardate 3219.8


More information about the Tkinter-discuss mailing list