How do I add text to a Text widget in Tkinter?


For reasons of simplicity, my "form" looks something like this:

import tkinter as tk

ventana = tk.Tk()

mensaje = tk.Text(ventana, background="white", width=165, height=25)
mensaje.pack(padx=0, pady=125)

mensaje.insert(INSERT, "Hola Mundo")


I understand that mensaje.insert(INSERT, "Hola Mundo") should add the required text to my widget, but I get this error:


File "", line 5, in       message.insert (INSERT, "Hello World") NameError: name 'INSERT' is not defined

What am I doing wrong?

asked by Kenny Barrera 28.09.2017 в 00:21

1 answer


INSERT is a variable defined within the module tkinter and that has as value the string 'insert' . Actually, according to the Python conventions it is a constant (identifier in uppercase should be treated as constants, keeping in mind that the concept of constant does not exist in Python as such.)

When belonging to the module tkinter and make the import of the form import tkinter as tk you have to indicate the namespace to which it belongs:

mensaje.insert(tk.INSERT, "Hola Mundo")

The confusion comes because much of tkinter's documentation leaks to the bullfighter what the PEPs and Python's own zen say about the imports. It is very common to be imported in the form from tkinter import * , this is generally a bad practice, the only possible justification is that they want to overwrite the widgets of tkinter with those of ttk, and even then I do not like:).

from tkinter import * imports all globals to the current namespace, so mensaje.insert(INSERT, "Hola Mundo") is valid. The problem is that this can cause collisions with other imports or with our own variables, populate the current namespace unnecessarily and end up not knowing clearly where everything comes from.

Python zen says:

  • Explicit better than implicit.
  • Namespaces are a good idea, let's make more of this.
  • Readability counts.

It does not make sense to throw it all away for saving us tk. (or std:: in C ++ and its using namespace std ...). With tk.INSERT we know who this variable belongs to and never enters into conflict with other variables called INSERT in our own module or in other imports.

Like the rest of constants as N , NW , CENTER , etc can be substituted in the methods where they are used replacing them by their value

mensaje.insert("insert", "Hola Mundo")

The method tkinter.Text.insert receives as the first argument the index where the text will be inserted, the second is the text itself and the third is a tuple with the labels associated with that text and that is optional. The index can be specified in many ways ( see documentation ). With tk.INSERT we indicate that the index where it should be inserted is the current position of the cursor in the widget Text .

Finally, indicate that you can not insert text either by code or by standard input if the Text has the status as "disabled" .

answered by 28.09.2017 / 16:08