Python tkinter entry textvariable

Python Tkinter Entry – How to use

In this Python tutorial, we will discuss in detail on Python tkinter entry.

  • Python Tkinter entry widget
  • Python Tkinter entry default value
  • Python Tkinter entry placeholder
  • Python Tkinter entry set text
  • Python Tkinter entry get text
  • Python Tkinter entry height
  • Python Tkinter entry text variable
  • Python Tkinter entry command on enter

Python Tkinter Entry

In Python, if you want to take user input in terms of single-line strings, then we should use Python Tkinter Entry. Let us check more on it.

Also, if you are new to Python GUI programming, check out the article Python GUI Programming (Python Tkinter) and How to create a Python Calculator using Tkinter.

Tkinter entry widget

  • Python tkinter Entry widgets are used to take user input.
  • It is a widely used widget and can be found on any application irrespective of the programming languages.
  • It is called TextField in java.
  • It is a one-liner box wherein the user can type something.
  • Unlike java, Tkinter does not have separate multiple line entry widgets.
  • To allow multiple line input, increase the height of the entry widget.

Tkinter entry default value

  • There is a thin line difference between placeholder & default value.
  • If the user will not provide any input then the default value will be used as an argument.
  • But in the case of placeholders, they can never be used as the value. they are placed to display information or pattern.
  • But in Tkinter default value & placeholders are the same
  • there are two ways of doing so:
    • Entry.insert
    • textvariable
    1. Entry.insert:
    • insert keyword is used to insert the word or sentence
    • END determines that next character should be entered immediately after the last character
    from tkinter import * ws = Tk() info_Tf = Entry(ws) info_Tf.insert(END, 'You email here') info_Tf.pack() ws.mainloop()

    Output: The output displays that text already mentioned in the textbox.

    Python Tkinter entry default value

    2. textvariable

    • textvariable is used to provide value through a variable
    • value can be Integer or String
    • for integer : IntVar() keyword is used
    • for String: StringVar() keyword is used
    from tkinter import * ws = Tk() name = StringVar(ws, value='not available') nameTf = Entry(ws, textvariable=name).pack() ws.mainloop()

    Output: In this output, if the user will not provide any information than ‘not available’ will be taken as default input’

    Tkinter entry placeholder

    Tkinter entry placeholder

    • Placeholders are the same as default values.
    • refer to Tkinter entry default value section

    Python Tkinter entry set text

    • Set text is used to set the text in the entry box in Python tkinter.
    • It is used with the function & plays the role of putting text in the entry box.
    • we will create a function & will call the function using button.
    • when user will click on the button the value will be inserted in entry box.

    In this code, there is a game in which you have to find a ring. Clicking on one of the box will get you a ring. Choose wisely.

    from tkinter import * def chooseOne(res): userInput.delete(0, END) userInput.insert(0, res) return ws = Tk() ws.title("find the ring") ws.geometry("400x250") frame = Frame(ws) userInput = Entry(frame, width=40, justify=CENTER) userInput.grid(row=0, columnspan=3, padx=5, pady= 10) Button(frame,text="Box 1",command=lambda:chooseOne("Nada!, try again")).grid(row=1, column=0) Button(frame,text="Box 2 ",command=lambda:chooseOne("Great! You found the ring")).grid(row=1, column=1) Button(frame,text="Box 3",command=lambda:chooseOne("Nada! try again")).grid(row=1, column=2) frame.pack() ws.mainloop()

    In this output, there is a game in which you have to find a ring. Clicking on one of the box will get you a ring . choose wisely

    Python Tkinter entry set text

    User failed to get the right button . Message “Nada, try again” is set in the entry box

    How to set text in Python Tkinter entry

    User pressed right button , message “Great! you found the ring” isset in the entry box.

    Python Tkinter entry get text

    • Get text is used to get the value from the Python Tkinter entry widget.
    • In other words, Get text pulls whatever value is provided by the user.
    • If you want to use the value that is provided by the user, then get the text is used.

    In this example, the User is providing his name, and the program prints the welcome message with his name.

    from tkinter import * from tkinter import messagebox ws = Tk() ws.title('get text demo') ws.geometry('200x200') def welcomeMessage(): name = name_Tf.get() return messagebox.showinfo('message',f'Hi! , Welcome to python guides.') Label(ws, text="Enter Name").pack() name_Tf = Entry(ws) name_Tf.pack() Button(ws, text="Click Here", command=welcomeMessage).pack() ws.mainloop()

    In this output, User has provided name as ‘Alpha’. Program is using this name to send a greeting message with the name.

    Tkinter entry get

    Python Tkinter entry height

    • Entry boxes are single line only
    • height is required to facilitate multiple line input.
    • height keyword is used & it takes an integer as input.
    • multiple line entry boxes are also called textarea.
    from tkinter import * ws = Tk() ws.geometry("400x250") text_area = Text(ws, height=10, width=30).pack() ws.mainloop()

    Entry box is single lined but in this example the white space is entry line. It can take multi-line input.

    Python Tkinter entry height

    PythonTkinter entry textvariable

    • textvariable is used to provide value through a variable
    • value can be Integer or String
    • for integer : IntVar() keyword is used
    • for String: StringVar() keyword is used.
    from tkinter import * ws = Tk() name = StringVar(ws, value='not available') nameTf = Entry(ws, textvariable=name).pack() ws.mainloop()

    Output: In this output, if the user will not provide any information than ‘not available’ will be taken as default input’

    Entry default value using textvariable

    Python Tkinter entry command on enter

    • It simply means, what action will happen when the user hits on Enter key on the keyboard.
    • This is also called key binding
    • Whenever users provide input in the entry widget & hits enter then some action is triggered.
    • the action could be in the form of validation, printing message, etc.
    • Let’s understand this better with an example
    • Write a code that prints a welcome message with the user’s name.
    • user will enter the name in the entry widget and then hit enter.
    • We are using bind function to perform above mentioned task
    • bind syntax: name_Tf.bind(», function)
    • In this case, the function is welMsg
    from tkinter import * from tkinter import messagebox ws = Tk() ws.title('pythonguides') ws.geometry('250x200') def welMsg(name): name = name_Tf.get() return messagebox.showinfo('pythonguides', f'Hi! , welcome to pythonguides' ) Label(ws, text='Enter Name & hit Enter Key').pack(pady=20) name_Tf = Entry(ws) name_Tf.bind('',welMsg) name_Tf.pack() ws.mainloop()

    So here, there is no button to trigger the function. User entered the name ‘Alpha’ and pressed enter. and the output greets him with his name.

    Tkinter entry command on enter

    You may like the following Python tutorials:

    • Python generate random number and string
    • Python tkinter label – How to use
    • Python write list to file with examples
    • Command errored out with exit status 1 python
    • Python epoch to DateTime + Examples
    • Priority queue in Python
    • Python 3 pickle typeerror a bytes-like object is required not ‘str’
    • Python Tkinter Button – How to use
    • Python Tkinter Progress bar
    • Create a Snake game in Python using Turtle
    • Python Tkinter Canvas Tutorial

    In this tutorial, we have studied entry widget in Python in details also we have covered these topics.

    • Python Tkinter entry widget
    • Python Tkinter entry default value
    • Python Tkinter entry placeholder
    • Python Tkinter entry set text
    • Python Tkinter entry get text
    • Python Tkinter entry height
    • Python Tkinter entry textvariable
    • Python Tkinter entry command on enter

    I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

    Источник

    Python tkinter entry textvariable

    Одной из примечательных особенностей Tkinter является то, что он позволяет привязать к ряду виджетов переменные определенных типов. При изменении значения виджета автоматически будет изменяться и значение привязанной переменной. Для привязки может использоваться переменная следующих типов:

    from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x150") message = StringVar() label = ttk.Label(textvariable=message) label.pack(anchor=NW, padx=6, pady=6) entry = ttk.Entry(textvariable=message) entry.pack(anchor=NW, padx=6, pady=6) button = ttk.Button(textvariable=message) button.pack(side=LEFT, anchor=N, padx=6, pady=6) root.mainloop()

    В данном случае определяется переменная message, которая представляет класс StringVar , то есть такая переменная, которая хранит некоторую строку.

    С помощью параметра textvariable эта переменная привязана к тексту поля Entry, а также к тексту кнопки и метки:

    ttk.Label(textvariable=message)

    И если мы изменим текст в поле Entry, автоматически синхронно изменится и значение привязанной переменной message. а поскольку к этой переменной также привязаны кнопка и метка, то автоматически также изменится текст метки и кнопки.

    Привязка переменной StringVar к виджету в Tkinter и Python

    Типы имеют параметр value , который позволяет установить значение по умолчанию. Кроме того, они имеют два метода:

    • get() : возвращает значение
    • set(value) : устанавливает значение, которое передано через параметр

    Применим эти методы. Например, мы могли бы установить привязку к переменной IntVar и выводить количество кликов:

    from tkinter import * from tkinter import ttk def click_button(): value = clicks.get() # получаем значение clicks.set(value + 1) # устанавливаем новое значение root = Tk() root.title("METANIT.COM") root.geometry("250x150") clicks = IntVar(value=0) # значение по умолчанию btn = ttk.Button(textvariable=clicks, command=click_button) btn.pack(anchor=CENTER, expand=1) root.mainloop()

    Изменение текста кнопки в Tkinter и Python

    Отслеживание изменения переменной

    Класс Stringvar позволяет отслеживать чтение и изменение своего значения. Для отслеживания у объекта StringVar вызывается метод trace_add()

    trace_add(trace_mode, function)

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

    Также можно передать список из этих значений, если нам надо отслеживать несколько событий.

    Второй параметр представляет функцию, которая будет вызываться при возникновении события из первого параметра. Эта функция должна принимать один параметр.

    from tkinter import * from tkinter import ttk def check(*args): print(name) if name.get()=="admin": result.set("запрещенное имя") else: result.set("норм") root = Tk() root.title("METANIT.COM") root.geometry("250x200") name = StringVar() result = StringVar() name_entry = ttk.Entry(textvariable=name) name_entry.pack(padx=5, pady=5, anchor=NW) check_label = ttk.Label(textvariable=result) check_label.pack(padx=5, pady=5, anchor=NW) # отслеживаем изменение значения переменной name name.trace_add("write", check) root.mainloop()

    В данном случае текстовое поле name_entry привязано к переменной name, а метка check_label — к переменной result.

    Здесь мы отлеживаем изменение значения переменной name — при изменении срабатывает функция check, в которой изменяем переменную result в зависимости от значения name. Условимся, что name представляет имя пользователя, но имя «admin» запрещено.

    Источник

    Читайте также:  Java использование абстрактных классов
Оцените статью