Python tkinter textbox set text

Tkinter Entry

Summary: in this tutorial, you’ll learn how to use the Tkinter Entry widget to create a textbox.

Introduction to Tkinter Entry widget

The Entry widget allows you to enter a sing-line text. In Tkinter, to create a textbox, you use the Entry widget:

textbox = ttk.Entry(container, **options)Code language: Python (python)
  • The container is the parent frame or window. on which you want to place the widget.
  • The options is one or more keyword arguments used to configure the Entry widget.

Note that if you want to enter multi-line text, you should use the Text widget.

To get the current text of a Entry widget as a string, you use the get() method:

textbox.get()Code language: Python (python)

Typically, you associate the current value of the textbox with a StringVar object like this:

text = tk.StringVar() textbox = ttk.Entry(root, textvariable=text)Code language: Python (python)
  • First, create a new instance of the StringVar class. The text will be the value holder for a string variable.
  • Second, assign the text variable to the textvariable of the Entry widget.

In this case, you can use call the get() method of the StringVar() object to get the current value of the entry widget:

text.get()Code language: CSS (css)

Setting the focus to the Tkinter Entry widget

To provide a better user experience, you can place move the focus to the first Entry widget after the window appears. Once the Entry widget has focus, it’s ready to accept the user input.

Читайте также:  Importing java lang math

To do it, you use the focus() method of the Entry widget like this:

textbox.focus()Code language: Python (python)

Showing a Tkinter password entry

To hide sensitive information on the Entry widget e.g., a password, you can use the show option.

The following creates a password entry. When you enter a password, it doesn’t show the actual characters but the asterisks (*) specified in the show option:

password = tk.StringVar() password_entry = ttk.Entry( root, textvariable=password, show='*' ) password_entry.pack()Code language: Python (python)

Tkinter Entry widget example

The following program shows how to use the Entry widgets to create a sign-in form:

import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo # root window root = tk.Tk() root.geometry("300x150") root.resizable(False, False) root.title('Sign In') # store email address and password email = tk.StringVar() password = tk.StringVar() def login_clicked(): """ callback when the login button clicked """ msg = f'You entered email: and password: ' showinfo( title='Information', message=msg ) # Sign in frame signin = ttk.Frame(root) signin.pack(padx=10, pady=10, fill='x', expand=True) # email email_label = ttk.Label(signin, text="Email Address:") email_label.pack(fill='x', expand=True) email_entry = ttk.Entry(signin, textvariable=email) email_entry.pack(fill='x', expand=True) email_entry.focus() # password password_label = ttk.Label(signin, text="Password:") password_label.pack(fill='x', expand=True) password_entry = ttk.Entry(signin, textvariable=password, show="*") password_entry.pack(fill='x', expand=True) # login button login_button = ttk.Button(signin, text="Login", command=login_clicked) login_button.pack(fill='x', expand=True, pady=10) root.mainloop()Code language: Python (python)

Tkinter Entry Example

First, create two string variables to hold the current text of the email and password Entry widgets:

# store email address and password email = tk.StringVar() password = tk.StringVar()Code language: Python (python)

Second, create the email Entry widget and associate it with the email variable:

email_entry = ttk.Entry(signin, textvariable=email)Code language: Python (python)

The following sets focus on the email entry:

email_entry.focus()Code language: Python (python)

Third, create the password entry widget and assign the password variable to its textvariable :

password_entry = ttk.Entry(signin, textvariable=password, show="*")Code language: Python (python)

Finally, display a message box that shows the entered email and password if the login button is clicked.

Summary

  • Use the ttk.Entry widget to create a textbox.
  • Use an instance of the StringVar() class to associate the current text of the Entry widget with a string variable.
  • Use the show option to create a password entry.

Источник

Python tkinter textbox set 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()

Источник

Оцените статью