简体   繁体   中英

Tkinter update label text in callback

Salutations, I've tried to find a problem that is similar to mine, but haven't managed. I am trying to update a ttk Label from the callback function that runs when changing the content of a ttk Entry. I tried to isolate the issue here:

import tkinter
from tkinter import ttk


def func():
    print("func!")
    lsv.set("CHANGED!")


# def func2():
#    return


root = tkinter.Tk()

frame = ttk.Frame(root)
frame.pack()

sv = tkinter.StringVar()
sv.trace_add("write", lambda *args: func())

entry = ttk.Entry(frame, textvariable=sv, width=25)
entry.pack()


lsv = tkinter.StringVar()
lsv.trace_add("read", ????). # lambda *args: func2() ?
lsv.set("Hello World")

label = ttk.Label(frame, text=lsv.get())
label.pack()

root.mainloop()

With this code, I manage to print out "func." every time I add text in the Entry, However. I don't understand how to get the label to change from "Hello World" to "CHANGED!".

I assume I need the trace_add in lsv . But I can't figure out exactly what else I need to do. The trace_add requires a callback function, so I tried just setting one that returns. (func2)

Would appreciate your help! Thanks

You're making things too hard. All you need is one StringVar that is the textvariable of both the Entry and the Label . You're function func isn't really needed, but I left it in.

import tkinter
from tkinter import ttk


def func():
    print("func!")
#    sv.set("CHANGED!")  # Not needed.


root = tkinter.Tk()

frame = ttk.Frame(root)
frame.pack()

sv = tkinter.StringVar()
sv.trace_add("write", lambda *args: func())

entry = ttk.Entry(frame, textvariable=sv, width=25)
entry.pack()

label = ttk.Label(frame, textvariable=sv)
label.pack()

entry.focus_set()
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM