Skip to main content
Engineering LibreTexts

10.5: More Widgets

  • Page ID
    15478
  • Tkinter provides two widgets that let users type text: an Entry, which is a single line, and a Text widget, which has multiple lines.

    en creates a new Entry:

    entry = g.en(text='Default text.')
    

    The text option allows you to put text into the entry when it is created. The get method returns the contents of the Entry (which may have been changed by the user):

    >>> entry.get()
    'Default text.'
    

    te creates a Text widget:

    text = g.te(width=100, height=5)
    

    width and height are the dimensions of the widget in characters and lines.

    insert puts text into the Text widget:

    text.insert(END, 'A line of text.')
    

    END is a special index that indicates the last character in the Text widget.

    You can also specify a character using a dotted index, like 1.1, which has the line number before the dot and the column number after. The following example adds the letters 'nother' after the first character of the first line.

    >>> text.insert(1.1, 'nother')
    

    The get method reads the text in the widget; it takes a start and end index as arguments. The following example returns all the text in the widget, including the newline character:

    >>> text.get(0.0, END)
    'Another line of text.\n'
    

    The delete method removes text from the widget; the following example deletes all but the first two characters:

    >>> text.delete(1.2, END)
    >>> text.get(0.0, END)
    'An\n'

    Exercise \(\PageIndex{1}\)

    Modify your solution to Exercise 19.3.1 by adding an Entry widget and a second button. When the user presses the second button, it should read a color name from the Entry and use it to change the fill color of the circle. Use config to modify the existing circle; don’t create a new one.

    Your program should handle the case where the user tries to change the color of a circle that hasn’t been created, and the case where the color name is invalid.

    Solution:

    http://thinkpython.com/code/circle_demo.py