How to modify a Label when writing in Entry on Tkinter?

Asked

Viewed 2,821 times

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, as I can 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()
  • I made a modification, but it still doesn’t work. It is http://pastebin.com/ntFJKPDJ

1 answer

1

For starters, 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:

  1. Use the same object StringVar either for the object Entry be for the 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()
    
  2. Do not use an object StringVar, but associate a call to a function with a certain event, in this case the event is <KeyRelease>, which practically happens when you stop pressing a button. In this function you can like control the content of the Label and compare it with the content of 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 don’t understand something, ask in the comments, and I edit the answer ;)

Browser other questions tagged

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