Search code examples
pythonpython-3.xtkintertkinter-entry

Print Tkinter Entry box value to a label


I am looking to simply print the value from a Tkinter Entry box into a label.

myLabel = ttk.Label(tab1, text="Enter your selection: ")
myLabel.grid(column=0, row=3)
labelEntry = tk.Entry(tab1)
labelEntry.grid(column=1, row=3, padx=10, pady=10)

Unfortunately I can't get my head around printing the value to a label. Is it possible to make it "live"? So as you are typing into the Entry text box the label populates too?

Also, how can I make the label be capitalised?

Is there an easy way to make this into a function instead of using lambda?

Thanks!


Solution

  • Use same tkinter StringVar on both the Entry and Label widgets:

    var1 = tk.StringVar()
    
    labelEntry = tk.Entry(tab1, textvariable=var1)
    labelEntry.grid(column=1, row=3, padx=10, pady=10)
    
    outputLabel = ttk.Label(tab1, textvariable=var1)
    outputLabel.grid(column=0, row=4, columnspan=2, padx=10, pady=10)
    

    Updated: if you want the content of the label be capitalized, then you can bind a trace callback on the tkinter StringVar instead and update the text of the label with capitalized content of the variable:

    var1 = tk.StringVar()
    labelEntry = tk.Entry(tab1, textvariable=var1)
    labelEntry.grid(column=1, row=3, padx=10, pady=10)
    
    outputLabel = ttk.Label(tab1)
    outputLabel.grid(column=0, row=4, columnspan=2, padx=10, pady=10)
    
    var1.trace_add('write', lambda *args:outputLabel.config(text=var1.get().upper()))