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

Confirmed what?

  1. Is every step behaving as expected?
  2. return statements were removed?

Confirmed every step behaving as expected and the return statement is removed both.

Hi Vikram,

Below is a version of your code that anyone can run without needing the rest of you codebase or your local files.

code
# coding: utf-8

import tkinter as tk
from tkinter import ttk, messagebox

textVar = ""
textVar1 = ""
canChannels = [1, 2, 3]


def update_text_var(_, arg):

    global textVar
    textVar = arg
    return


def validate_input(user_input):

    global textVar
    if textVar == "baudRate":
        valid_decimal_char = lambda charac: charac in '0123456789'
        return (len(user_input) < 7) and (all(valid_decimal_char(userInputChar)
                                              for userInputChar
                                              in user_input.lower()))
    elif textVar == "txCANId" or textVar == "rxCANId":
        valid_hex_char = lambda charac: charac in 'ABCDEF0123456789'
        return (len(user_input) < 5) and (all(valid_hex_char(userInputChar)
                                              for userInputChar
                                              in user_input.upper()))
    elif user_input == "":
        return True
    else:
        return False


# fourth window frame ProjectConfigPage
class ProjectConfigPage(ttk.Frame):

    def __init__(self):

        super(ProjectConfigPage, self).__init__()
        global textVar1
        global canChannels

        self.xmlTxCANId = "23"
        self.xmlRxCANId = "58"
        self.xmlBaudRate = "94"
        self.xmlUSBChannelNumber = ""

        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.theme_use('clam')
        self.buttonStyle.configure('flat.TButton', borderwidth=0,
                                   relief='groove')

        self.homeButton = ttk.Button(self.firstSubFrame, style='flat.TButton',
                                     text="Home Page",
                                     compound=tk.TOP)
        self.homeButton.grid(row=0, column=0, rowspan=2, columnspan=2,
                             sticky=tk.NW, padx=5, pady=5)

        self.backButton = ttk.Button(self.firstSubFrame, style='flat.TButton',
                                     text="Back Page",
                                     compound=tk.TOP)
        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,
                                 anchor=tk.W)
        self.txCANId.grid(row=2, column=4, columnspan=2)

        textVar1 = "txCANId"
        self.txCANIdUserInput = ttk.Entry(self.firstSubFrame, width=23,
                                          state=tk.NORMAL)
        self.txCANIdUserInput.insert(0, self.xmlTxCANId)

        self.txCANIdUserInput.grid(row=2, column=6, sticky=tk.NSEW)
        self.userInput1 = self.firstSubFrame.register(validate_input)
        self.txCANIdUserInput.bind(
          "<Key>", lambda event, arg=textVar1: update_text_var(event, arg))
        self.txCANIdUserInput.config(validate="key",
                                     validatecommand=(self.userInput1, '%P'))

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

        textVar1 = "rxCANId"
        self.rxCANIdUserInput = ttk.Entry(self.firstSubFrame, width=23,
                                          state=tk.NORMAL)
        self.rxCANIdUserInput.insert(0, self.xmlRxCANId)
        self.rxCANIdUserInput.grid(row=4, column=6, sticky=tk.NSEW)
        self.userInput1 = self.firstSubFrame.register(validate_input)
        self.rxCANIdUserInput.bind(
          "<Key>", lambda event, arg=textVar1: update_text_var(event, arg))
        self.rxCANIdUserInput.config(validate="key",
                                     validatecommand=(self.userInput1, '%P'))

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

        textVar1 = "baudRate"
        self.baudRateUserInput = ttk.Entry(self.firstSubFrame, width=23,
                                           state=tk.NORMAL)
        self.baudRateUserInput.insert(0, self.xmlBaudRate)
        self.baudRateUserInput.grid(row=6, column=6, sticky=tk.NSEW)
        self.userInput1 = self.firstSubFrame.register(validate_input)
        self.baudRateUserInput.bind(
          "<Key>", lambda event, arg=textVar1: update_text_var(event, arg))
        self.baudRateUserInput.config(validate="key",
                                      validatecommand=(self.userInput1, '%P'))

        self.usbChannel = ttk.Label(self.firstSubFrame,
                                    text="USB Channel Number", width=25,
                                    font=("bold", 10), justify=tk.LEFT,
                                    anchor=tk.W)
        self.usbChannel.grid(row=8, column=4, columnspan=2)
        self.usbChannelCombobox = ttk.Combobox(self.firstSubFrame,
                                               state="readonly")
        self.usbChannelCombobox['values'] = canChannels
        self.usbChannelCombobox.current(0)
        self.usbChannelCombobox.grid(row=8, column=6, sticky=tk.NSEW)

        self.saveButton = ttk.Button(self.firstSubFrame, style='flat.TButton',
                                     text="Save Configuration",
                                     compound=tk.TOP)
        self.saveButton.grid(row=12, column=0, rowspan=3, columnspan=3,
                             sticky=tk.SW, padx=5, pady=5)

        self.uploadButton = ttk.Button(self.firstSubFrame,
                                       style='flat.TButton',
                                       text="Upload Configuration",
                                       compound=tk.TOP)
        self.uploadButton.config(command=lambda: [self.upload_config()])
        self.uploadButton.grid(row=12, column=4, rowspan=3, columnspan=3,
                               sticky=tk.SW, padx=5, pady=5)

        self.clearButton = ttk.Button(self.firstSubFrame, style='flat.TButton',
                                      text="Clear Configuration",
                                      compound=tk.TOP)
        self.clearButton.config(command=lambda: [self.clear_config()])
        self.clearButton.grid(row=12, column=8, rowspan=3, columnspan=3,
                              sticky=tk.SW, padx=5, pady=5)

        self.applyButton = ttk.Button(self.firstSubFrame, style='flat.TButton',
                                      text="Apply Configuration",
                                      compound=tk.TOP)
        self.applyButton.grid(row=12, column=12, rowspan=3, columnspan=3,
                              sticky=tk.SW, padx=5, pady=5)

    def clear_config(self):

        print(self.txCANIdUserInput)
        print(self.rxCANIdUserInput)
        print(self.baudRateUserInput)
        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)
        self.txCANIdUserInput.focus_set()
        self.update()
        self.update_idletasks()
        return

    def upload_config(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!!!")
            return
        else:
            self.txCANIdUserInput.insert(0, self.xmlTxCANId)
            self.rxCANIdUserInput.focus_set()
            self.rxCANIdUserInput.insert(0, self.xmlRxCANId)
            self.baudRateUserInput.focus_set()
            self.baudRateUserInput.insert(0, self.xmlBaudRate)
        return


class Main(tk.Tk):

  def __init__(self):

    super().__init__()
    self._frame = ProjectConfigPage()
    self._frame.pack()


if __name__ == '__main__':

    main = Main()
    main.mainloop()

Clicking on the “Upload Configuration” button does work for me, the fields are getting updated (I set the CAN IDs to non-empty strings in __init__). Your error is very likely in the part of your code that parses XML and that I removed.

That I have already confirmed the xml data is coming correctly.
Parsing is happening without any issues.

Just because no error is displayed doesn’t mean the code is behaving as it should !

What my code sample demonstrates is just: with self.xmlTxCANId = "23", your code is able to upload the self.txCANIdUserInput field when self.uploadButton is clicked, which is I think the intended behavior.
Whether self.xmlTxCANId should be a string in this format, and what value it should it take when parsing an XML file, only you can know for sure.

Is your code missing one line of code (the first one):

        else:
            self.txCANIdUserInput.focus_set()                 # Focus on cell
            self.txCANIdUserInput.insert(0, self.xmlTxCANId)  # Write to cell
            
            self.rxCANIdUserInput.focus_set()                 # Focus on cell
            self.rxCANIdUserInput.insert(0, self.xmlRxCANId)  # Write to cell
            
            self.baudRateUserInput.focus_set()                # Focus on cell
            self.baudRateUserInput.insert(0, self.xmlBaudRate)# Write to cell

I tried with setting focus also still it did not work.

Hello dear all responders,

I am thankful to all of you for helping me resolve this issue.
I dropped use of insert method instead I am using textvariable and passing string to it.
This second approach is updating values for me as expected hence I am going with it.

Thanks and Regards,
Vikram Kashelikar

1 Like

Just one small test for your reference, can you try replacing the 0 with tk.INSERT to see if that would have worked in the else statements? If not, you have already found a workaround.