username123 username123 - 2 months ago 13
Python Question

Why can't the contents in these three entries change simultaneously?

Firstly let's look at this program:

def entry_simutaneously_change():
from Tkinter import *

root=Tk()
text_in_entry.set(0)

Entry(root, width=30, textvariable= text_in_entry).pack()
Entry(root, width=30, textvariable= text_in_entry).pack()
Entry(root, width=30, textvariable= text_in_entry).pack()

root.mainloop()


The contents in these three entries can change simultaneously. If I change the value of any of them, the other two would change at the same time. However, for the following program:

def entry_simutaneously_change():
from Tkinter import *

root=Tk()
text_in_entry_list=[IntVar() for i in range(0,3)]
text_in_entry_list[0].set(0)
text_in_entry_list[1].set(text_in_entry_list[0].get() ** 2)
text_in_entry_list[2].set(text_in_entry_list[0].get() ** 3)

Entry(root, width=30, textvariable= text_in_entry_list[0]).pack()
Entry(root, width=30, textvariable= text_in_entry_list[1]).pack()
Entry(root, width=30, textvariable= text_in_entry_list[2]).pack()

root.mainloop()


When I change the content in the first entry, the contents in the other two do not change. Why?

Answer Source

In the first program, you have one source of data, text_in_entry. You could consider it as one box where you're placing a single value that's read by each Entry.

In the second program, you have three sources of data, text_in_entry[0, 1, and 2]. The lines that set the initial value are called only once. It's like you have three boxes where data is placed; to set the initial values, you do look at the value inside the first, but there is no association between the three.

If you would like to achieve the same type of result as with the first program (when the three entries update simultaneously) then you will need to bind on an event. I note that Tkinker does not have an on-change style event but there are various hacks, however you could bind to the FocusOut event. The general idea is to ask for a function to be called when a change occurs to an entry (binding a callback). Inside that function you update the other two values based on the new value in the entry that was changed.