Python tkinter text методы

Tkinter Text

Summary: in this tutorial, you’ll learn how to use the Tkinter Text widget to add a text editor to your application.

Introduction to Tkinter Text widget

The Text widget allows you to display and edit multi-line textarea with various styles. Besides the plain text, the Text widget supports embedded images and links.

To create a text widget, you use the following syntax:

text = tk.Text(master, conf=<>, **kw)
  • The master is the parent component of the Text widget.
  • The cnf is a dictionary that specifies the widget’s configuration.
  • The kw is one or more keyword arguments used to configure the Text widget.

Note that the Text widget is only available in the Tkinter module, not the Tkinter.ttk module.

The following example creates a Text widget with eight rows and places it on the root window:

from tkinter import Tk, Text root = Tk() root.resizable(False, False) root.title("Text Widget Example") text = Text(root, height=8) text.pack() root.mainloop()Code language: JavaScript (javascript)

Tkinter Text

In this example, the height argument specifies the number of rows of the Text widget.

Inserting initial content

To insert contents into the text area, you use the insert() method. For example:

from tkinter import Tk, Text root = Tk() root.resizable(False, False) root.title("Text Widget Example") text = Text(root, height=8) text.pack() text.insert('1.0', 'This is a Text widget demo') root.mainloop()Code language: JavaScript (javascript)

Tkinter Text Widget

The first argument of the insert() method is the position where you want to insert the text.

The position has the following format:

'line.column'Code language: JavaScript (javascript)

In the above example, ‘1.0’ means line 1, character 0, which is the first character of the first line on the text area.

Retrieving the text value

To retrieve the contents of a Text widget, you use its get() method. For example:

text_content = text.get('1.0','end')Code language: JavaScript (javascript)

The get() method accepts two arguments. The first argument is the start position, and the second is the end position.

To retrieve only part of the text, you can specify different start and end positions.

Disabling the Text widget

To prevent users from changing the contents of a Text widget, you can disable it by setting the state option to ‘disabled’ like this:

text['state'] = 'disabled'Code language: JavaScript (javascript)

To re-enable editing, you can change the state option back to normal :

text['state'] = 'normal'Code language: JavaScript (javascript)

Summary

Источник

Python tkinter text методы

Для добавления текста применяется метод insert() :

Первый параметр представляет позицию вставки в формате «line.column» — сначала идет номер строки, а затем номер символа. Второй параметр — собственно вставляемый текст. Например, вставка в начало:

Для вставки в конец для позиции передается значение END :

from tkinter import * root = Tk() root.title("METANIT.COM") root.geometry("250x200") editor = Text() editor.pack(fill=BOTH, expand=1) editor.insert("1.0", "Hello World") # вставка в начало editor.insert(END, "\nBye World") # вставка в конец root.mainloop()

Добавление строк в виджет Test в tkinter и python

Получение текста

Для получения введенного текста применяется метод get() :

Параметр start указывает на начальный символ, а end — на конечный символ, текст между которыми надо получить. Оба параметра в формате «line.colunm», где line — номер строки, а «column» — номер символа. Для указания последнего символа применяется константа END:

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("300x200") editor = Text(height=5) editor.pack(anchor=N, fill=X) label=ttk.Label() label.pack(anchor=N, fill=BOTH) def get_text(): label["text"] = editor.get("1.0", "end") button = ttk.Button(text="Click", command=get_text) button.pack(side=BOTTOM) root.mainloop()

В данном случае по нажатию на кнопку срабатывает функция get_text() , которая получает текст и передается его для отображения в метку label:

Получение введенного текста из виджета Test в tkinter и python

Удаление текста

Для удаления текста применяется метод delete()

Параметр start указывает на начальный символ, а end — на конечный символ, текст между которыми надо удалить. Оба параметра в формате «line.colunm», где line — номер строки, а «column» — номер символа. Для указания последнего символа применяется константа END. Например, определим кнопку, которая будет удалять весь текст из виджета:

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("300x200") editor = Text(height=10) editor.pack(anchor=N, fill=BOTH) def delete_text(): editor.delete("1.0", END) button = ttk.Button(text="Clear", command=delete_text) button.pack(side=BOTTOM) root.mainloop()

Замена текста

Для замены текста применяется метод replace() :

Параметр start указывает на начальный символ, а end — на конечный символ, текст между которыми надо заменить. Оба параметра в формате «line.colunm», где line — номер строки, а «column» — номер символа. Для указания последнего символа применяется константа END. Последний параметр — chars — строка, на которую надо заменить. Например, замена первых четырех символов на строку «дама»:

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("300x200") editor = Text(height=10) editor.pack(anchor=N, fill=BOTH) editor.insert("1.0", "мама мыла раму") def edit_text(): editor.replace("1.0", "1.4", "дама") button = ttk.Button(text="Replace", command=edit_text) button.pack(side=BOTTOM) root.mainloop()

Замена текста в виджете Test в tkinter и python

Повтор и отмена операций

Методы edit_undo() и edit_redo() позволяют соответственно отменить и повторить операцию (добавление, изменение, удаление текста). Данные методы применяются, если в виджете Text параметр undo равен True. Стоит отметить, что данные методы оперируют своим стеком операций, в котором сохраняются данные операций. Однако если стек для соответствующего метода пуст, то вызов метода вызывает исключение. Простейший пример, где по нажатию на кнопку вызывается отмена или возврат операции:

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") root.grid_columnconfigure(0, weight = 1) root.grid_columnconfigure(1, weight = 1) root.grid_rowconfigure(0, weight = 1) editor = Text(undo=True) editor.grid(column = 0, columnspan=2, row = 0, sticky = NSEW) def undo(): editor.edit_undo() def redo(): editor.edit_redo() redo_button = ttk.Button(text="Undo", command=undo) redo_button.grid(column=0, row=1) clear_button = ttk.Button(text="Redo", command=redo) clear_button.grid(column=1, row=1) root.mainloop()

Выделение текста

Для управления выделением текста виджет Text обладает следующими методами:

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") def get_selection(): label["text"]=editor.selection_get() def clear_selection(): editor.selection_clear() editor = Text(height=5) editor.pack(fill=X) label = ttk.Label() label.pack(anchor=NW) get_button = ttk.Button(text="Get selection", command=get_selection) get_button.pack(side=LEFT) clear_button = ttk.Button(text="Clear", command=clear_selection) clear_button.pack(side=RIGHT) root.mainloop()

В данном случае по нажатию на кнопку get_button срабатывает функция get_selection, которая передает в метку label выделенный текст. При нажатии на кнопку clear_button срабатывает функция clear_selection, которая снимает выделение.

События

Достаточно часто встречает необходимость обработки ввода текста. Для виджета Text определено событие > , которое срабатывает при изменении текста в текстовом поле. Однако оно срабатывает один раз. И в этом случае мы можем обработать стандартные события клавиатуры. Например, событие освобождения клавиши :

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") def on_modified(event): label["text"]=editor.get("1.0", END) editor = Text(height=8) editor.pack(fill=X) editor.bind("", on_modified) label = ttk.Label() label.pack(anchor=NW) root.mainloop()

В данном случае при освобождении клавиши будет срабатывать функция on_modified , в которой метке label передается весь введенный текст:

обработка ввода текста в Tkinter и Python

Другую распространенную задачу представляет динамическое получение выделенного текста. В этом случае мы можем обработать событие > . Например, при выделении текста выведем выделенный фрагмент в метку Label:

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") def on_modified(event): label["text"]=editor.selection_get() editor = Text(height=8) editor.pack(fill=X) editor.bind(">", on_modified) label = ttk.Label() label.pack(anchor=NW) root.mainloop()

Источник

Читайте также:  Переделать xml в html
Оцените статью