您在這裡

More widgets

8 九月, 2015 - 10:52

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 19.3. Modify your solution to Exercise 19.2 in Canvas widgets 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 configto 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.

You can see my solution at http: // thinkpython. com/ code/ circle_ demo. py.