Jack Bond Jack Bond - 3 months ago 9
Python Question

Python: How to change text of a message widget to a user input

So I'm making a program which requires a user to enter in a value. I want the value to be displayed via the message widget (or label widget) and updates whenever a new input is enter.

def Enter():
s = v.get()
print (v.get())

e.delete(0, END)
e.insert(0, "")

#Code, Code, Code
...

# Area To Enter Text
v = StringVar()
e = Entry(root, textvariable=v)
e.pack()

m = Message(root, text = "Your Input")
m.pack()

# Enter Button
b = Button(root, text="OK", command=Enter)
b.pack()


Is there a way for the variable of v to replace the text of Message Widget??

Note:

If I replace
text
with
textvariable
, it updates the text after every character key is pressed, where as I need it to update when the user presses the button.




My complete code:

from tkinter import *
import os

# All Functions Below
def callback():
print ("HI")

def Exit():
os._exit(0)

def Enter():
s = e.get()
print (e.get())
m.configure(text=s)
e.delete(0, END)
e.insert(0, "")

def Population():
root = Tk

root.mainloop()

def SurvivalRate():
root = Tk

root.mainloop()

def BirthRate():
root = Tk

root.mainloop()

def NewGen():
root = Tk

root.mainloop()

root = Tk()


generation = 0

menubar = Menu(root)
menubar.add_command(label="Hello!", command=callback)
menubar.add_command(label="Quit!", command=Exit)


# Area To Enter Text
e = Entry(root)
e.pack()

m = Message(root, text = e)
m.pack()

# Enter Button
b = Button(root, text="OK", command=Enter)
b.pack()

Pop = Button(root, text="Population", command=Population)
Pop.pack()

Answer

Simply add:

m.configure(text=s) 

to your function:

def Enter():
    s = v.get()
    print (v.get())
    m.configure(text=s)
    e.delete(0, END)
    e.insert(0, "")

As a side- note, you do not necessarily need the StringVar(). The code below will do exactly the same:

def Enter():
    s = e.get()
    m.configure(text=s)
    e.delete(0, END)
    e.insert(0, "")

#Code, Code, Code
...

# Area To Enter Text
e = Entry(root)
e.pack()

m = Message(root, text = "Your Input")
m.pack()

# Enter Button
b = Button(root, text="OK", command=Enter)
b.pack()

root.mainloop()