How it works...

Our Text widget is initially empty, and it has a width of 50 characters and a height of 10 lines. Apart from allowing users to enter any type of text, we will dive into the methods used by each button to have a better understanding of how to interact with this widget.

The delete(start, end) method removes the content from the start index to the end index. If the second parameter is omitted, it only deletes the character at the start position.

In our example, we delete all the text by calling this method from the 1.0 index (column 0 of the first line) to the tk.END index, which refers to the last character:

def clear_text(self):
self.text.delete("1.0", tk.END)

The insert(index, text) method inserts the given text at the index position. Here, we call it with the INSERT index, which corresponds to the position of the insertion cursor:

def insert_text(self):
self.text.insert(tk.INSERT, "Hello, world")

The tag_ranges(tag) method returns a tuple with the first and last indices of all the ranges with a given tag. We used the special tk.SEL tag to refer to the current selection. If there is no selection, this call would return an empty tuple. This is combined with the get(start, end) method, which returns the text in a given range:

def print_selection(self):
selection = self.text.tag_ranges(tk.SEL)
if selection:
content = self.text.get(*selection)
print(content)

Since the SEL tag corresponds to only one range, we can safely unpack it to call the get method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset