Python tkinter entry параметры

Python tkinter entry параметры

Элемент Entry представляет поле для ввода текста. С помощью конструктора Entry можно установить ряд параметров, основные из них:

  • background : фоновый цвет
  • cursor : курсор указателя мыши при наведении на текстовое поле
  • foreground : цвет текста
  • font : шрифт текста
  • justify : устанавливает выравнивание текста. Значение LEFT выравнивает текст по левому краю, CENTER — по центру, RIGHT — по правому краю
  • show : задает маску для вводимых символов
  • state : состояние элемента, может принимать значения NORMAL (по умолчанию) и DISABLED
  • textvariable : устанавливает привязку к элементу StringVar
  • width : ширина элемента

Элемент Entry имеет ряд методов. Основные из них:

  • insert(index, str) : вставляет в текстовое поле строку по определенному индексу
  • get() : возвращает введенный в текстовое поле текст
  • delete(first, last=None) : удаляет символ по индексу first. Если указан параметр last, то удаление производится до индекса last. Чтобы удалить до конца, в качестве второго параметра можно использовать значение END.
  • focus() : установить фокус на текстовое поле

Простейшее текстовое поле:

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") ttk.Entry().pack(anchor=NW, padx=8, pady= 8) root.mainloop()

текстовое поле ввода Entry в tkinter и python

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

Для получения текста из Entry, можно использовать его метод get() . Так, определим элемент Entry и по нажатию на кнопку выведем введенный текст на текстовую метку:

from tkinter import * from tkinter import ttk def show_message(): label["text"] = entry.get() # получаем введенный текст root = Tk() root.title("METANIT.COM") root.geometry("250x200") entry = ttk.Entry() entry.pack(anchor=NW, padx=6, pady=6) btn = ttk.Button(text="Click", command=show_message) btn.pack(anchor=NW, padx=6, pady=6) label = ttk.Label() label.pack(anchor=NW, padx=6, pady=6) root.mainloop()

получение текста из текстового поля Entry в tkinter в Python

Вставка и удаление текста

Рассмотрим вставку и удаление текста в Entry:

from tkinter import * from tkinter import ttk def clear(): entry.delete(0, END) # удаление введенного текста def display(): label["text"] = entry.get() # получение введенного текста root = Tk() root.title("METANIT.COM") root.geometry("250x150") label = ttk.Label() label.pack(anchor=NW, padx=6, pady=6) entry = ttk.Entry() entry.pack(anchor=NW, padx=6, pady=6) # вставка начальных данных entry.insert(0, "Hello World") display_button = ttk.Button(text="Display", command=display) display_button.pack(side=LEFT, anchor=N, padx=6, pady=6) clear_button = ttk.Button(text="Clear", command=clear) clear_button.pack(side=LEFT, anchor=N, padx=6, pady=6) root.mainloop()

При запуске программы в текстовое поле сразу же добавляется текст по умолчанию:

Кнопка Clear очищает оба поля, вызывая метод delete:

def clear(): entry.delete(0, END)

Вторая кнопка, используя метод get, получает введенный текст:

def display(): label["text"] = entry.get()

Валидация

С помощью параметра validate конструктора Entry можно задать, когда проводить валидацию введенного значения. Этот параметр может принимать следующие значения:

  • none : отсутствие валидации, значение по умолчанию
  • focus : валидация при получении фокуса
  • focusin : валидация при изменении фокуса
  • focusout : валидация при потере фокуса
  • key : валидация при каждом вводе нового символа
  • all : валидация при измении фокуса и вводе символов в поле
Читайте также:  What are closures in javascript

Параметр validatecommand позволяет установить команду валидации.

Рассмотрим небольшой пример. Допустим, пользовтаель должен ввести номер телефона в формете +xxxxxxxxxxx. То есть сначала должен идти знак +, а затем 11 цифр, например, +12345678901:

from tkinter import * from tkinter import ttk import re def is_valid(newval): return re.match("^\+\d$", newval) is not None root = Tk() root.title("METANIT.COM") root.geometry("250x200") check = (root.register(is_valid), "%P") phone_entry = ttk.Entry(validate="key", validatecommand=check) phone_entry.pack(padx=5, pady=5, anchor=NW) root.mainloop()

Итак, параметр validate=»key» указывает, что мы будем валидировать ввод при каждом нажати на клавиатуру. Параметр validatecommand=check говорит, что валидировать ввод будет команда «check». Эта команда представляет кортеж из двух элементов:

check = (root.register(is_valid), "%P")

Первый элемент — вызов метода root.register(is_valid) регистрирует функцию, которая собственно будет производить валидацию — это функция is_valid() . Второй элемент — подстановка «%P» представляет новое значение, которое передается в функцию валидации.

Собственно саму валидацию выполняет функция is_valid() . Она принимает один параметр — текущее значение Entry, которое надо валидировать. Она возвращает True, если значение прошло валидацию, и False, если не прошло. Сама логика валидации представляет проверку строки на регулярное выражение «^\+\d*$» . Если новое значение соответствует этому выражению, и в нем не больше 12 символов, то оно прошло валидацию.

В итоге мы сможем ввести в текстовое поле только символ + и затем только 11 цифр.

Валидация ввода в entry на tkinter в Python

Теперь немного изменим код и добавим вывод ошибок валидации:

from tkinter import * from tkinter import ttk import re def is_valid(newval): result= re.match("^\+\d$", newval) is not None if not result and len(newval) 

Здесь для вывода ошибок валидации добавлен виджет Label. Если введенное значение не соответствует регулярному выражению (например, пользователь попытался ввести нецифровой символ), и длина ввода меньше и равно 12 символов (проверять ввод больше 12 символов нет смысла, так как номер телефона содержит только 12 символов), то в метке выводим сообщение об ошибке

Валидация ввода в entry и вывод сообщения об ошибке в tkinter в Python

Также мы можем передать значение параметра validate, чтобы в функции валидации в зависимости от того, нажал пользователь на клавишу или убрал фокус с поля, производить те или иные действия. В этом случае необходимо передать команде валидации дополнительный аргумент:

check = (root.register(is_valid), "%P", "%V")

Здесь значение "%V" представляет событие, которое вызывает валидацию (focus/focusin/focusout/key). Тогда в функции валидации с помощью второго параметра мы сможем получить это значение:

def is_valid(newval, op): result= re.match("^\+\d$", newval) is not None if op=="key": # некоторые действия elif op=="focus": # некоторые действия return result

Источник

Python - Tkinter Entry

The Entry widget is used to accept single-line text strings from a user.

  • If you want to display multiple lines of text that can be edited, then you should use the Text widget.
  • If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget.

Syntax

Here is the simple syntax to create this widget −

Parameters

  • master − This represents the parent window.
  • options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

The normal background color displayed behind the label and indicator.

The size of the border around the indicator. Default is 2 pixels.

A procedure to be called every time the user changes the state of this checkbutton.

If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton.

The font used for the text.

By default, if you select text within an Entry widget, it is automatically exported to the clipboard. To avoid this exportation, use exportselection=0.

The color used to render the text.

The color of the focus highlight when the checkbutton has the focus.

If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT.

With the default value, relief=FLAT, the checkbutton does not stand out from its background. You may set this option to any of the other styles

The background color to use displaying selected text.

The width of the border to use around selected text. The default is one pixel.

The foreground (text) color of selected text.

Normally, the characters that the user types appear in the entry. To make a .password. entry that echoes each character as an asterisk, set show="*".

The default is state=NORMAL, but you can use state=DISABLED to gray out the control and make it unresponsive. If the cursor is currently over the checkbutton, the state is ACTIVE.

In order to be able to retrieve the current text from your entry widget, you must set this option to an instance of the StringVar class.

The default width of a checkbutton is determined by the size of the displayed image or text. You can set this option to a number of characters and the checkbutton will always have room for that many characters.

If you expect that users will often enter more text than the onscreen size of the widget, you can link your entry widget to a scrollbar.

Methods

Following are commonly used methods for this widget −

delete ( first, last=None )

Deletes characters from the widget, starting with the one at index first, up to but not including the character at position last. If the second argument is omitted, only the single character at position first is deleted.

Returns the entry's current text as a string.

Set the insertion cursor just before the character at the given index.

Shift the contents of the entry so that the character at the given index is the leftmost visible character. Has no effect if the text fits entirely within the entry.

Inserts string s before the character at the given index.

select_adjust ( index )

This method is used to make sure that the selection includes the character at the specified index.

Clears the selection. If there isn't currently a selection, has no effect.

Sets the ANCHOR index position to the character selected by index, and selects that character.

If there is a selection, returns true, else returns false.

select_range ( start, end )

Sets the selection under program control. Selects the text starting at the start index, up to but not including the character at the end index. The start position must be before the end position.

Selects all the text from the ANCHOR position up to but not including the character at the given index.

This method is useful in linking the Entry widget to a horizontal scrollbar.

xview_scroll ( number, what )

Used to scroll the entry horizontally. The what argument must be either UNITS, to scroll by character widths, or PAGES, to scroll by chunks the size of the entry widget. The number is positive to scroll left to right, negative to scroll right to left.

Example

Try the following example yourself −

from Tkinter import * top = Tk() L1 = Label(top, text="User Name") L1.pack( side = LEFT) E1 = Entry(top, bd =5) E1.pack(side = RIGHT) top.mainloop()

When the above code is executed, it produces the following result −

Источник

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