How to update and show in real time on label 2 what user write in ENTRY label1?

Question:

If i have this ENTRY label1 on pos1, how can i update and show "in real time" the text i write on other label 2 in position2?

label1 = Entry(root, font=('aria label', 15), fg='black')
label1.insert(0, 'enter your text here')
label1_window = my_canvas.create_window(10, 40, window=entry)

label2 = how to update and show in real time what user write on label1
Asked By: DoritoDorito

||

Answers:

Issues in your attempt: The variable names are not clear as you are creating an Entry component and then assigning it to a variable named label1 which can be confusing.

Hints: You can do one of the following to tie the label to the entry so that changing the text in the entry causes the text in the label to change:

  1. Use a shared variable
  2. Implement a suitable callback function. You can, for example, update the label each time the KeyRelease event occurs.

Solution 1 – Shared variable: Below is a sample solution using a shared variable:

import tkinter as tk
from tkinter import *

root = tk.Tk()
root.title('Example')
root.geometry("300x200+10+10")

user_var = StringVar(value='Enter text here')

user_entry = Entry(root, textvariable=user_var, font=('aria label', 15), fg='black')
user_entry.pack()

echo_label = Label(root, textvariable=user_var)
echo_label.pack()

root.mainloop()

Solution 2 – Callback function: Below is a sample solution using a suitable callback function. This is useful if you wish to do something more:

import tkinter as tk
from tkinter import *

root = tk.Tk()
root.title('Example')
root.geometry("300x200+10+10")


def user_entry_changed(e):
    echo_label.config({'text': user_entry.get()})


user_entry = Entry(root, font=('aria label', 15), fg='black')
user_entry.insert(0, 'Enter your text here')
user_entry.bind("<KeyRelease>", user_entry_changed)
user_entry.pack()

echo_label = Label(root, text='<Will echo here>')
echo_label.pack()

root.mainloop()

Output: Here is the resulting output after entering 'abc' in the entry field:

enter image description here

Answered By: Prins

If the entry and label use the same StringVar For the textvariable option, the label will automatically show whatever is in the entry. This will happen no matter whether the entry is typed in, or you programmatically modify the entry.

import tkinter as tk

root = tk.Tk()
var = tk.StringVar()

canvas = tk.Canvas(root, width=400, height=200, background="bisque")
entry = tk.Entry(root, textvariable=var)
label = tk.Label(root, textvariable=var)

canvas.pack(side="top", fill="both", expand=True)
label.pack(side="bottom", fill="x")

canvas.create_window(10, 40, window=entry, anchor="w")

root.mainloop()

enter image description here

Answered By: Bryan Oakley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.