Python - Assign the value of an entry to a variable

Asked

Viewed 1,583 times

2

I tried to use the command mensagem = str(entry.get()) but it doesn’t work, I tried to use the entry = Entry(root, textvariable='mensagem') but also does not work, see the whole code basically want to type something in an entry and printar on the console..

from tkinter import *
mensagem = str
def enviar():
    mensagem = str(entry.get())
    print(mensagem)

root = Tk()

entry = Entry(root, textvariable=mensagem).place(x=10, y=10)
button = Button(root, text='ENVIAR', command=enviar).place(x=30, y=40)

root.mainloop() 

2 answers

1

from tkinter import *

root = Tk()

mensagem = str

entry = Entry(root)
entry.pack()


def enviar():
    mensagem = str(entry.get())
    print(mensagem)


button = Button(root, text='ENVIAR', command=enviar)
button.pack()

root.mainloop()

Just add the . pack() and initialize the entry before function, so python can access this variable

http://effbot.org/tkinterbook/entry.htm

1

def enviar():
    texto = mensagem.get()
    print(texto)

When you use a variable associated with an Entry, you must make the calls to get and set for the variable. Kinter ("message") as the name of a local variable within the function, the first was not visible to Python - you would have the error that you were trying to access the local variable before assigning it.

Just use the global name "message" to avoid collisions with the local variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.