Search code examples
pythonvariablestkintertkinter-entry

Why are two Entry boxes with the same 'text =' values treated as the same entry box?


I've asked a question about text being inserted into two entry boxes when it should only be inserted into one. The problem lines of code turned out to be these:

MoneyAvailableTextBox = Entry(temp, font=('arial', 14, 'bold'), bg='White', fg = 'Black', bd = 5, width = 10, borderwidth = 4,  justify = CENTER, text = '£')
MoneyAvailableTextBox.grid(row = 1, column = 0, pady = 10)

HeistAwardTextBox = Entry(temp, font=('arial', 14, 'bold'), bg='White', fg = 'Black', bd = 5, width = 10, borderwidth = 4,  justify = CENTER, text = '£')
HeistAwardTextBox.grid(row = 3, column = 0, pady = 10)

A friend of mine eventually figured out what the issue was and I answered my own question in case someone else comes across this issue. The issue was that both entry boxes had text = '£'. My friend simply changed one of them to have the value $ and the issue was solved. Deleting them also stops the issue. Neither he nor I am sure why having to entry boxes with the same text = '£' makes them be treated as the same entry box.

I've replicated the problem down below. I've simplified the code.

import tkinter as tk
from tkinter import*

trialGUI = Tk()
trialGUI.title('Text Boxes')

#This is the text which will be inserted
value1 = 'Hello'
value2 = 'Bye'

#This inserts the text into the entry boxes
def updateStats():
    entryBox1.delete('0', END)
    #This should insert Hello in the first box
    entryBox1.insert(tk.INSERT, value1)
    entryBox2.delete('0', END)
    #This should insert Bye in the second box
    entryBox2.insert(tk.INSERT, value2)

# These are the text boxes
entryBox1 = Entry(trialGUI, text = '£')
entryBox1.grid(row = 0)
entryBox2 = Entry(trialGUI, text = '£')
entryBox2.grid(row = 1)

#Button which when pressed inserts texting into the entry boxes
Button1 = Button(trialGUI, command = updateStats, text = 'Insert Text')
Button1.grid(row = 2)

trialGUI.mainloop()

How I said, this issue has been solved. I'm just looking for an explanation why the problem occurs in the first place.


Solution

  • text option is the same as textvariable option for Entry widget. Since you passed a string "£" to it but not an instance of StringVar, an instance of StringVar will be created with the string as its name implicitly for you. So both Entry widgets are using same StringVar. Therefore changing one of the them will also change the other as they share the same StringVar.