Where do I make a mistake with this tkinter focus?

Viewed 19

I made a tool to add multiple order numbers in our system. The first time a row of entry cells is placed the focus is where it should be. But the second time the focus is not in the new left cell. First I thought it has to do with using the tab key. But if I understand the code correct, I first execute the moving of the tab key and then execute the code. So the command to focus on the new left cell is last.

Where am I going wrong?

import tkinter as tk
from tkinter import ttk

# Create variables for later use
order_list = []
date_list = []
row_number = 0
active_order_entry = None
active_date_entry = None


def add_a_row_of_entry_cells():
    global row_number
    global active_order_entry
    global active_date_entry

    row_number += 1

    order_entry = ttk.Entry()
    order_entry.grid(row=row_number, column=0)
    order_entry.focus()

    date_entry = ttk.Entry()
    date_entry.grid(row=row_number, column=1)

    # Make these entries the active ones
    active_order_entry = order_entry
    active_date_entry = date_entry

    # Add entries to a list
    order_list.append(order_entry)
    date_list.append(date_entry)


def tab_pressed(event):
    if active_order_entry.get() != "" and active_date_entry.get() != "":
        add_a_row_of_entry_cells()
    else:
        print("Order, date or both are not filled yet")


def button_pressed():
    print("Button pressed")


# Create window
window = tk.Tk()

# Add function to the Tab key
window.bind("<Tab>", tab_pressed)

# Labels on top of the columns
label_order_number = tk.Label(window, text="Order", fg="#22368C")
label_order_number.grid(row=row_number, column=0)
label_date = tk.Label(window, text="Date", fg="#22368C")
label_date.grid(row=row_number, column=1)

# Create empty row
empty_row = tk.Label(window)
empty_row.grid(row=87, column=0)

# Create button
button = tk.Button(window, text="Add orders", command=lambda: button_pressed())
button.grid(row=98, column=0, columnspan=3)

# Create empty row
empty_row = tk.Label(window)
empty_row.grid(row=99, column=0)

# Add the first row
add_a_row_of_entry_cells()

window.mainloop()
0 Answers
Related