Ádám Koczka
Ádám Koczka

Reputation: 23

Import tkinter as tk does not work with text widget

I tried to create a text widget with option import tkinter as tk but I don't know why the text methods not working with my object. If I use from tkinter import * then it is all good, but as I read this is not the recommended importing method. So, could you please advise why first code works and the second doesn't? What am I missing?

This works:

from tkinter import *

root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()

root.mainloop()

This doesn't:

import tkinter as tk

root = tk.Tk()
text = tk.Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()

root.mainloop()

Thanks

Upvotes: 0

Views: 216

Answers (1)

ncica
ncica

Reputation: 7206

if you are using:

import Tkinter as tk

INSERT is a constant defined in Tkinter, so you also need to precede it with Tkinter.

you need to use INSERT like:

tk.INSERT

your code:

import tkinter as tk

root = tk.Tk()
text = tk.Text(root)
text.insert(tk.INSERT, "Hello.....")
text.insert(tk.END, "Bye Bye.....")
text.pack()

root.mainloop()

in this case if you are using :

text.insert(INSERT, "Hello.....")

you will get an error:

NameError: name 'INSERT' is not defined

Upvotes: 2

Related Questions