How to connect a variable to Entry widget?

后端 未结 1 631
花落未央
花落未央 2020-12-17 22:13

I\'m trying to associate a variable with a Tkinter entry widget, in a way that:

  1. Whenever I change the value (the \"content\") of the entry, mainly by typing

相关标签:
1条回答
  • 2020-12-17 22:40

    I think you want something like this. In the example below, I created a variable myvar and assigned it to be textvariable of both a Label and Entry widgets. This way both are coupled and changes in the Entry widget will reflect automatically in Label.

    You can also set trace on variables, e.g. to write to stdout.

    from tkinter import *
    
    
    root = Tk()
    root.title("MyApp")
    
    myvar = StringVar()
    
    def mywarWritten(*args):
        print "mywarWritten",myvar.get()
    
    myvar.trace("w", mywarWritten)
    
    label = Label(root, textvariable=myvar)
    label.pack()
    
    text_entry = Entry(root, textvariable=myvar)
    text_entry.pack()
    
    root.mainloop()
    
    0 讨论(0)
提交回复
热议问题