Insert function not working for multiple entry boxes created in tkinter python3 when trying to insert values on click of a button

Hello python experts,

I have created three entry boxes and I have created two buttons first button uploads xml content directly onto the entry boxes on click and second button clears the entry boxes.
I see that the upload button which uploads the xml file content onto the entry boxes is not working because the insert method is not working when the page gets loaded
Following is the code where you can see the class project config page which contains the methods uploadConfig and clearConfig etc. I am seeing that the insert method called inside uploadConfig function is not working.
I have already verified that the contents are getting captured successfully from the xml file but not getting uploaded to entry boxes on click of a button.
Your help is appreciated thanks in advance:

#Function used to update the global variable textVar as it is used in validateInput function
def updateTextVar(event, arg):
    global textVar
    textVar = arg

#Function which validates the input given by user and accepts only the number value
#def validateInput(action, userInput, content, value):
def validateInput(userInput):
    global textVar
    if textVar == "baudRate":
        validDecimalChar = lambda charac: charac in '0123456789'
        return (len(userInput) < 7) and (all(validDecimalChar(userInputChar) for userInputChar in userInput.lower()))
    elif textVar == "txCANId" or textVar == "rxCANId":
        validHexChar = lambda charac: charac in 'ABCDEF0123456789'
        return (len(userInput) < 5) and (all(validHexChar(userInputChar) for userInputChar in userInput.upper()))
    elif userInput == "":
        return True
        return False

# fourth window frame ProjectConfigPage
class ProjectConfigPage(ttk.Frame):
    def __init__(self, parent, controller):
        super(ProjectConfigPage, self).__init__()
        #super(ProjectConfigPage, self).__init__()
        #ttk.Frame.__init__(self, parent)
        global textVar1
        global canChannels
        #global xmlTxCANId
        #global xmlRxCANId
        #global xmlBaudRate
        #global xmlUSBChannelNumber

        self.xmlTxCANId = ""
        self.xmlRxCANId = ""
        self.xmlBaudRate = ""
        self.xmlUSBChannelNumber = ""
        #self.constVal1 = tk.StringVar()
        #self.constVal2 = tk.StringVar()
        #self.constVal3 = tk.StringVar()
        self.bind_all("<Button-1>", self.onEvent)
        self.tree = ET.parse(r"D:\Python_PCAN_Project\Python_PCAN_HW_Communication\config.xml")
        self.xmlRoot = self.tree.getroot()

        #self.xmlTxCANId = list(self.xmlRoot[0])[0].text
        #self.xmlRxCANId = list(self.xmlRoot[0])[1].text
        #self.xmlBaudRate = list(self.xmlRoot[0])[2].text
        #self.xmlUSBChannelNumber = list(self.xmlRoot[0])[3].text

        for elementIndex in range(len(list(self.xmlRoot[0]))):
            if elementIndex == 0:
                self.xmlTxCANId = list(self.xmlRoot[0])[elementIndex].text
            elif elementIndex == 1:
                self.xmlRxCANId = list(self.xmlRoot[0])[elementIndex].text
            elif elementIndex == 2:
                self.xmlBaudRate = list(self.xmlRoot[0])[elementIndex].text
            elif elementIndex == 3:
                self.xmlUSBChannelNumber = list(self.xmlRoot[0])[elementIndex].text


        self.widget = ""
        self.firstSubFrame = ttk.Frame(self)
        self.firstSubFrame.grid(row=0, column=0, columnspan=15, rowspan=14, sticky=tk.N)

        self.buttonStyle = ttk.Style(self)
        self.buttonStyle.configure('flat.TButton', borderwidth=0, relief='groove')

        self.homeButtonPhoto ="D:\Python_PCAN_Project\Python_PCAN_HW_Communication\Images\home_button.png")
        self.homeButtonImage = self.homeButtonPhoto.resize((35,35))
        self.homeButtonImage = ImageTk.PhotoImage(image=self.homeButtonImage)
        self.homeButton = ttk.Button(self.firstSubFrame, style='flat.TButton', text="Home Page", image=self.homeButtonImage, compound=tk.TOP)
        self.homeButton.config(command=lambda: [controller.show_frame(StartPage)])
        self.homeButton.grid(row=0, column=0, rowspan=2, columnspan=2, sticky=tk.NW, padx=5, pady=5)

        self.backButtonPhoto ="D:\Python_PCAN_Project\Python_PCAN_HW_Communication\Images\back_button.png")
        self.backButtonImage = self.backButtonPhoto.resize((35,35))
        self.backButtonImage = ImageTk.PhotoImage(image=self.backButtonImage)
        self.backButton = ttk.Button(self.firstSubFrame, style='flat.TButton', text="Back Page", image=self.backButtonImage, compound=tk.TOP)
        self.backButton.config(command=lambda: [controller.show_frame(SettingsAndConfigPage)])
        self.backButton.grid(row=0, column=13, rowspan=2, columnspan=2, sticky=tk.NE, padx=5, pady=5)

        self.txCANId = ttk.Label(self.firstSubFrame, text="txCANId", width=25, font=("bold", 10), justify=tk.LEFT,
        self.txCANId.grid(row=2, column=4, columnspan=2)

        textVar1 = "txCANId"
        self.txCANIdUserInput = ttk.Entry(self.firstSubFrame, width=23, state= tk.NORMAL)
        #self.txCANIdUserInput = ttk.Entry(self.firstSubFrame, width=23, textvariable=self.constVal1)
        #self.txCANIdUserInput.insert(tk.END, "00")
        #self.txCANIdUserInput.insert(0, "00")
        self.txCANIdUserInput.insert(0, self.xmlTxCANId)
        #self.txCANIdUserInput.insert(0, "Enter txCANId here.")
                      #lambda event: self.txCANIdUserInput.delete(0, "end") if self.ConstVal.get() == "Enter txCANId here." else None)
                      #lambda event: self.txCANIdUserInput.insert(0, "Enter txCANId here.") if self.ConstVal.get() == "" else None)
                      #lambda event: self.txCANIdUserInput.insert(0, "Enter txCANId here."))

        self.txCANIdUserInput.grid(row=2, column=6, sticky=tk.NSEW)
        self.userInput1 = self.firstSubFrame.register(validateInput)
        self.txCANIdUserInput.bind("<Return>", self.onReturn)
        self.txCANIdUserInput.bind("<Key>", lambda event, arg=textVar1: updateTextVar(event, arg))
        self.txCANIdUserInput.config(validate="key", validatecommand=(self.userInput1, '%P'))
        #self.txCANIdUserInput.config(validate="key", validatecommand=(self.userInput1,'%d','%S','%s', '%P'))
        CreateToolTip(self.txCANIdUserInput, 'Please enter positive hexadecimal value. The value should not exceed uint32_t size.')

        self.rxCANId = ttk.Label(self.firstSubFrame, text="rxCANId", width=25, font=("bold", 10), justify=tk.LEFT,
        self.rxCANId.grid(row=4, column=4, columnspan=2)

        textVar1 = "rxCANId"
        self.rxCANIdUserInput = ttk.Entry(self.firstSubFrame, width=23, state= tk.NORMAL)
        #self.rxCANIdUserInput = ttk.Entry(self.firstSubFrame, width=23, textvariable=self.constVal2)
        #self.rxCANIdUserInput.insert(tk.END, "00")
        #self.rxCANIdUserInput.insert(0, "00")
        self.rxCANIdUserInput.insert(0, self.xmlRxCANId)
        self.rxCANIdUserInput.grid(row=4, column=6, sticky=tk.NSEW)
        self.userInput1 = self.firstSubFrame.register(validateInput)
        self.rxCANIdUserInput.bind("<Return>", self.onReturn)
        self.rxCANIdUserInput.bind("<Key>", lambda event, arg=textVar1: updateTextVar(event, arg))
        self.rxCANIdUserInput.config(validate="key", validatecommand=(self.userInput1, '%P'))
        #self.rxCANIdUserInput.config(validate="key", validatecommand=(self.userInput1,'%d','%S','%s', '%P'))
        CreateToolTip(self.rxCANIdUserInput, 'Please enter positive hexadecimal value. The value should not exceed uint32_t size.')

        self.baudRate = ttk.Label(self.firstSubFrame, text="baudRate", width=25, font=("bold", 10), justify=tk.LEFT,
        self.baudRate.grid(row=6, column=4, columnspan=2)

        textVar1 = "baudRate"
        self.baudRateUserInput = ttk.Entry(self.firstSubFrame, width=23, state= tk.NORMAL)
        #self.baudRateUserInput = ttk.Entry(self.firstSubFrame, width=23, textvariable=self.constVal3)
        #self.baudRateUserInput.insert(tk.END, "00")
        #self.baudRateUserInput.insert(0, "00")
        self.baudRateUserInput.insert(0, self.xmlBaudRate)
        self.baudRateUserInput.grid(row=6, column=6, sticky=tk.NSEW)
        self.userInput1 = self.firstSubFrame.register(validateInput)
        self.baudRateUserInput.bind("<Return>", self.onReturn)
        self.baudRateUserInput.bind("<Key>", lambda event, arg=textVar1: updateTextVar(event, arg))
        self.baudRateUserInput.config(validate="key", validatecommand=(self.userInput1, '%P'))
        #self.baudRateUserInput.config(validate="key", validatecommand=(self.userInput1,'%d','%S','%s', '%P'))
        CreateToolTip(self.baudRateUserInput, 'Please enter positive decimal value. The value should not exceed uint32_t size.')

        self.usbChannel = ttk.Label(self.firstSubFrame, text="USB Channel Number", width=25, font=("bold", 10), justify=tk.LEFT,
        self.usbChannel.grid(row=8, column=4, columnspan=2)
        self.usbChannelCombobox = ttk.Combobox(self.firstSubFrame, state="readonly")
        self.usbChannelCombobox['values'] = (canChannels)
        #self.usbChannelCombobox['values'] = (self.comboChannels)
        #self.usbChannelCombobox.bind("<Button-1>", self.onButtonClick)
        #self.usbChannelCombobox.bind("<<ComboboxSelected>>", self.onComboboxSelection)
        self.usbChannelCombobox.grid(row=8, column=6, sticky=tk.NSEW)

        self.saveButtonPhoto ="D:\Python_PCAN_Project\Python_PCAN_HW_Communication\Images\save_button.png")
        self.saveButtonImage = self.saveButtonPhoto.resize((35,35))
        self.saveButtonImage = ImageTk.PhotoImage(image=self.saveButtonImage)
        self.saveButton = ttk.Button(self.firstSubFrame, style='flat.TButton', text="Save Configuration", image=self.saveButtonImage, compound=tk.TOP)
        #self.saveButton.config(command=lambda: [controller.show_frame(StartPage)])
        self.saveButton.grid(row=12, column=0, rowspan=3, columnspan=3, sticky=tk.SW, padx=5, pady=5)

        self.uploadButtonPhoto ="D:\Python_PCAN_Project\Python_PCAN_HW_Communication\Images\upload_config_button.png")
        self.uploadButtonImage = self.uploadButtonPhoto.resize((35,35))
        self.uploadButtonImage = ImageTk.PhotoImage(image=self.uploadButtonImage)
        self.uploadButton = ttk.Button(self.firstSubFrame, style='flat.TButton', text="Upload Configuration", image=self.uploadButtonImage, compound=tk.TOP)
        #self.uploadButton.config(command=lambda: [uploadProjectConfig(self)])
        self.uploadButton.config(command=lambda: [self.uploadConfig()])
        #self.uploadButton.bind("<Button-1>", lambda event: (self.uploadConfig(event)))
        #self.uploadButton.bind("<Button-1>", lambda event: (self.uploadConfig(event), self.txCANIdUserInput.insert(0, self.xmlTxCANId)))
        self.uploadButton.grid(row=12, column=4, rowspan=3, columnspan=3, sticky=tk.SW, padx=5, pady=5)

        self.clearButtonPhoto ="D:\Python_PCAN_Project\Python_PCAN_HW_Communication\Images\clear_config_button.png")
        self.clearButtonImage = self.clearButtonPhoto.resize((35,35))
        self.clearButtonImage = ImageTk.PhotoImage(image=self.clearButtonImage)
        self.clearButton = ttk.Button(self.firstSubFrame, style='flat.TButton', text="Clear Configuration", image=self.clearButtonImage, compound=tk.TOP)
        self.clearButton.config(command=lambda: [self.clearConfig()])
        self.clearButton.grid(row=12, column=8, rowspan=3, columnspan=3, sticky=tk.SW, padx=5, pady=5)

        self.applyButtonPhoto ="D:\Python_PCAN_Project\Python_PCAN_HW_Communication\Images\apply_config_button.png")
        self.applyButtonImage = self.applyButtonPhoto.resize((35,35))
        self.applyButtonImage = ImageTk.PhotoImage(image=self.applyButtonImage)
        self.applyButton = ttk.Button(self.firstSubFrame, style='flat.TButton', text="Apply Configuration", image=self.applyButtonImage, compound=tk.TOP)
        #self.applyButton.config(command=lambda: [controller.show_frame(StartPage)])
        self.applyButton.grid(row=12, column=12, rowspan=3, columnspan=3, sticky=tk.SW, padx=5, pady=5)

    def clearConfig(self):
        print("1 Inside clearConfig")
        if self.txCANIdUserInput.get():
            self.txCANIdUserInput.delete(0, tk.END)
        if self.rxCANIdUserInput.get():
            self.rxCANIdUserInput.delete(0, tk.END)
        if self.baudRateUserInput.get():
            self.baudRateUserInput.delete(0, tk.END)

    def uploadConfig(self):
        print("2 Inside uploadConfig")
        if self.txCANIdUserInput.get() != "" or self.rxCANIdUserInput.get() != "" or self.baudRateUserInput.get() != "":
            messagebox.showwarning("Warning", "Please clear all the visible values using clear configuration button then press upload button!!!")
            self.txCANIdUserInput.insert(0, self.xmlTxCANId)
            self.rxCANIdUserInput.insert(0, self.xmlRxCANId)
            self.baudRateUserInput.insert(0, self.xmlBaudRate)

Please see the pinned thread and format the code properly so that we can see and understand it properly; then please explain what “not working” means: exactly what do you see happening, as you try using the program, step by step? Exactly what should you see happening instead, and how is that different?

What is the purpose of the returns in the functions? I don’t see a return expression or value?

Thanks for the reply dear Paul,

The clearConfig() function has return but the UI works fine when I click on clear button it clears the entry boxes properly. Only problem is with the uploadConfig() function which is not uploading values in the entry boxes even when using the insert functions.

Vikram Kashelikar

Note that functions by default return None. So, if you’re not returning anything explicitly, there is no need to have them. You can remove them since they are not adding value to the code.

You appear to have posted the same code twice. If so, please delete 2nd.

Error examples should be a small as possible to show the claimed issue so we can better focus on what code is relevant. Can you remove as much as is unneeded?

Hello dear Terry,

Actual code is 5000 lines.
I have taken only the relevant part from the code and posted it so that you can focus on only the required part. which is one class and its methods only that to only two methods for two buttons.

Vikram Kashelikar

From reviewing the header to the function, it appears that you want to check if three different values are clear via the if conditional statement. Just so that I understand this, do all three have to be clear or only one is enough?

Hello dear Paul,

All three values should be cleared hence I am checking all three in if condition.

Thanks and Regards,
Vikram Kashelikar

Can you please explain what you want this function to do. What does it check and under what conditions should code be executed and not executed.

I did a quick search of the function in your code. You are calling it as shown here:

self.uploadButton.config(command=lambda: [self.uploadConfig()])

I think that this is the wrong way to set it up.
You should have it as:

self.uploadButton.config(command= self.uploadConfig)

The lambda is used if you have an expression. Here you do not.

Also, make correction here:

self.clearButton.config(command=lambda: [self.clearConfig()])

This should be:

self.clearButton.config(command = self.clearConfig)

Please check all of your code and make sure it follows this format.

Hello Paul,

So inside my class there are two functions one function to clear all the entered values from the entry boxes on click of clear button for that I have created clearConfig() function.
And there is another function called uploadConfig() which uploads values taken from an xml file and uploads it onto the entry boxes on click of upload button.
I have already verified that the values are getting captured correctly from the xml file.
Only thing is the insert function is not entering values back into the entry boxes as expected.

Thanks and Regards,
Vikram Kashelikar

Before moving further, can you please correct the code per my previous post.

That I already did no difference I saw in the behavior.

When you press the button, do you verify that the following print statement is executed:

print("2 Inside uploadConfig")

Yes exactly that is what I see in the console.
And that is the reason for keeping this print statement.

Thanks and Regards,
Vikram Kashelikar

Include a print statement inside the if statement and one in the else statement inside the function. Where do you expect the flow of the program to go into? Verify that it is going in the expected direction.

Simultaneously, print the values for the three variables:


This way we verify what is being read and if the code is behaving as we expect it to step by step.
Also, remove the return statements since they are not doing anything.

That I already did and got “” from the entry boxes after the insert method was executed that is how I confirmed that insert is not working.

Vikram Kashelikar

Ok, so from the function, the only part that is actually doing any work is the else statement. The if statement only prints a warning. From the following code, what is it that you want the code to do?:

self.txCANIdUserInput.insert(0, self.xmlTxCANId)
self.rxCANIdUserInput.insert(0, self.xmlRxCANId)
self.baudRateUserInput.insert(0, self.xmlBaudRate)

Have you verified step by step the resultant values after each statement? This way we verify if the issue is within the function or if the issue is coming from outside the function.

Also, have you removed the return statements?

Yes Paul,
I verified and confirmed.
Also I removed the return statement.