简体   繁体   中英

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 presses the "Enter" key on keyboard or clicks on "Calculate" button, the place where he entered the number "5" should also display 10, besides the place immediately below. Normally, the form keeps the number entered , but the place right below it gets updated and displays 10 (let us say you have entered 5)

How can I also update the form place?

(Please let me know if my question is unclear, so I can better explain myself.)

from tkinter import *

def multiplier(*args):
    try:
        value = float(ment.get())
        result.set(value * 2)
    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()

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()

The StringVar s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM