Skip to content Skip to sidebar Skip to footer

Updating Text In Entry (tkinter)

The piece of code below takes input from user through a form and then returns the input as multiplied by 2. What I want to do is, when a user types a number (for example 5) and pre

Solution 1:

You can use Entry's delete and insert methods.

from tkinter import *

def multiplier(*args):
    try:
        value = float(ment.get())
        res = value *2
        result.set(res)
        mEntry.delete(0, END) #deletes the current value
        mEntry.insert(0, res) #inserts new value assigned by 2nd parameter

    except ValueError:
        pass

mGui = Tk()
mGui.geometry("300x300+300+300")

ment = StringVar()
result = StringVar()

mbutton = Button (mGui, text = "Calculate", command = multiplier)
mbutton.pack()

mEntry = Entry(mGui, textvariable = ment, text="bebe")
mEntry.pack()

mresult = Label(mGui, textvariable = result)
mresult.pack()

Solution 2:

The StringVars you update via the set method, which you're doing in the multiplier function. So you question is how to trigger the call the multiplier when the user presses enter, you can use:

    mGui.bind('<Return>', multiplier)

Do you also want to change the text in the Entry? The question is a bit unclear. You can do that via ment.set as well.

Post a Comment for "Updating Text In Entry (tkinter)"