Shubham Kumar
Shubham Kumar

Reputation: 121

How to insert text in textPad from an entry box in Python 2 Tkinter?

There are an Entry box and a textPad in my code and a Button for the event.
When the button is pressed it reads the value from entry and prints it into textPad.

My code is:

from Tkinter import *
import os
import ScrolledText
root = Tk()
root.geometry('500x500')
top = Frame(root)
top.pack()
root.title('TextPad')

def run():
    cmd = entry.get()
    textPad.insert(cmd)
entry = Entry(top,font='Helvetica 15',width=40)
entry.grid(row=1,column=1)
btn = Button(top,text='Run',command=run)
btn.grid(row=1,column=2)
textPad = ScrolledText.ScrolledText(root,font='Helvetica 10', width=100, height=80)
textPad.pack()
root.mainloop()

It does not print on textPad, gives an exception

Exception in Tkinter callback
Traceback (most recent call last):
  File "/home/pir4t3/anaconda2/lib/python2.7/lib-tk/Tkinter.py", line 1542, in __call__
    return self.func(*args)
  File "<ipython-input-22-3bad83384d34>", line 13, in run
    textPad.insert(cmd)
TypeError: insert() takes at least 3 arguments (2 given)

Upvotes: 0

Views: 300

Answers (1)

GaryMBloom
GaryMBloom

Reputation: 5682

The insert(pos, newstring, tags=[]) command from the Text widget takes at least two, but possibly three, arguments. You got an error because you only entered one argument.

The first arg is the index in the Text widget where you want to insert newstring. For an empty Text widget, Tkinter.END (or just END, since you've done from Tkinter import *) will insert newstring at the end of the widget. "1.0" would insert newstring at the very beginning of the Text widget (row 1, column 0). See the below link for a more comprehensive explanation of Text indexes.

newstring is the actual new string you want to insert.

tags allows you to "tag" newstring with any formatting tag names you have defined. You can use these to change fonts, colors, etc.

See http://effbot.org/tkinterbook/text.htm for more details.

Also, you entered:

textPad.insert(cmd)

and you got the error msg:

TypeError: insert() takes at least 3 arguments (2 given)

It says you've given 2 args. cmd is actually the 2nd. textPad is considered the 1st "argument" passed to the .insert() method, due to object orientation. It may not seem intuitive, but that's the way it is. :)

Upvotes: 2

Related Questions