How to modify a Label when writing in Entry in tkinter?

6

I would like to make a program that detects the change in the Entry text and changes the Label to the same Entry text, how can I do this?

from tkinter import *

# Configurações da Tela
window = Tk()
window.title("Hello World")  
window.resizable(width=False, height=False)
window.geometry("300x300")

TextoLabel = StringVar()
TextoLabel.set("AAAAAA")
#Criando uma funcao para dar update na Label


# Widgets
entrada = Entry(window)
lbl = Label(textvariable = TextoLabel)
b = Button(text="see ya?!")

# Mostrar todos os itens na tela
b.pack()
entrada.pack()
lbl.pack()
window.mainloop()

while True:
    if entryname.get() == "":
        TextoLabel.set("Nada")
        window.update_idletasks()
    else:
        TextoLabel.set(entryname.get())
        window.update_idletasks()
    
asked by anonymous 17.07.2015 / 16:11

1 answer

0

To begin, I advise against using loops in tkinter, because they will interfere with mainloop .

What you want to do can be done in at least two ways:

  • Using the same object StringVar is for the object Entry and for Label , which is as simple as the following:

    from tkinter import *
    
    
    root = Tk()
    
    prompt = Label(root, text="Insere algo")
    prompt.pack(side="left")
    
    entry_content = StringVar()
    
    # Associando "entry_content" a propriedade "textvariable".
    # O que escreves no "entry" é "absorvido" pelo "entry_content"
    
    entry = Entry(root, textvariable=entry_content) 
    entry.pack(side="left")
    
    # O valor do "entry_content" é modificado no "entry"
    # E essa modificação vai-se refletir nesta "label"    
    
    label = Label(root, text="", textvariable=entry_content)
    label.pack(side="left")
    
    root.mainloop()
    
  • Do not use an object StringVar , but bind a call to a function with a certain event, in which case the event is <KeyRelease> , which almost happens when you stop loading a key. In this function you can type control the contents of the Label and compare it with the contents of the Entry.

    from tkinter import *
    
    
    root = Tk()
    
    prompt = Label(root, text="Insere algo")
    prompt.pack(side="left")
    
    entry = Entry(root)
    entry.pack(side="left")
    
    
    def on_key_pressing(event, entry, label):
        print(entry.get(), label.cget("text"))
        if entry.get() != label.cget("text"):
            label.config(text=entry.get())
    
    # Associando o evento <Key> com a chamada
    # a funcão on_key_pressing
    entry.bind("<KeyRelease>", lambda e: on_key_pressing(e, entry, label))
    
    label = Label(root, text="")
    label.pack(side="left")
    
    root.mainloop()
    
  • If you do not understand something, ask in the comments, and I edit the answer;)

        
    21.07.2015 / 03:54