For the sake 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.config(state="disable")
mensaje.pack(padx=0, pady=125)
mensaje.insert(INSERT, "Hola Mundo")
ventana.mainloop()
I understand that I mensaje.insert(INSERT, "Hola Mundo")
should add the required text to my widget, but I get this error:
File "search.py", line 5, in message.insert(INSERT, "Hello World") NameError: name 'INSERT' is not defined
What am I doing wrong?
INSERT
is a variable defined inside the moduletkinter
and that has as value the string'insert'
. Actually, according to Python conventions it is a constant (identifier in capital letters should be treated as constants, keeping in mind that the concept of a constant does not exist in Python as such.)When belonging to the module
tkinter
and performing the import of the form,import tkinter as tk
you must indicate the namespace to which it belongs:The confusion comes because much of the tkinter documentation ignores what PEPs and Python's own zen say about imports. It is very common to import in the form
from tkinter import *
, this is generally a bad practice, the only possible justification is that you want to overwrite tkinter widgets with ttk ones, and even then I don't like it :).from tkinter import *
imports all globals into the current namespace, so itmensaje.insert(INSERT, "Hola Mundo")
's valid. The problem is that this can cause collisions with other imports or with our own variables, it populates the current namespace unnecessarily and we end up not clearly knowing where everything came from.The Zen of Python says:
There's no point in throwing it all away to save us
tk.
(orstd::
in C++ and itsusing namespace std
...). Withtk.INSERT
we know who that variable belongs to and it never conflicts with other variables calledINSERT
in our own module or in other imports.Like the rest of constants such as
N
,NW
,CENTER
, etc, they can be substituted in the methods where they are used, replacing them with their valueThe method
tkinter.Text.insert
receives as its first argument the index where the text is going to be inserted, the second is the text itself and the third is a tuple with the labels associated with that text and which is optional. The index can be specified in many ways ( see documentation ). Withtk.INSERT
we indicate that the index where it should be inserted is the current position of the cursor in the widgetText
.Finally, indicate that text cannot be inserted either through code or through standard input if it
Text
has the status as"disabled"
.