Search code examples
python-3.xtkintertkinter-entry

Switching the source of a tkinter Entry textVariable


Forgive the title, since this one hasn't been so easy to explain well with such a small amount of characters.

This is Python, of course, using tkinter and the Entry widget.

So what I have is an Entry, and I also have a class. It's a very simple class and looks like this:

class Class1():
    def __init__(self):
        self.strVar = tk.StringVar()

The class, in fact, was created just to try and replicate this particular problem.

Then we need two instances of this class, as well as a 'selected' one. That is, a pointer to whichever of the two instances we want.

c1 = Class1()
c1.strVar.set('First')
c2 = Class1()
c2.strVar.set('Second')

selectedClass = c1

Next, we need to set the textVariable of the Entry widget to strVar of 'selectedClass':

entry1 = tk.Entry(frame1, textvariable=selectedClass.strVar)

If it's not clear, my aim is to be able to now swap selectedClass; rather, point it to another instance (like c2) and then have the Entry's text change as a result. This is not what's happening.

The value is changing, though. I have a button linked to this command:

def ChangeSelected():
    global selectedClass

    print(f'Before: {selectedClass.strVar.get()}')
    selectedClass = c2
    print(f'After: {selectedClass.strVar.get()}')

selectedClass is certainly changing, because those two print statements show that we get 'First' for the first one and 'Second' for the second one. The Entry text, however, still shows 'First'. It has not updated.

So what I would like is for the Entry to be updated too. In my C# WPF days you could... well, the situation is a bit different it seems, but you could call 'RaisePropertyChanged' and it would update observers of a variable (like text boxes and what not).


Solution

  • You need to manually change the textvariable attribute of the entry widget:

    entry1.configure(textvariable=c2.strVar)