Home > Enterprise >  Is there any way when I enter text in Entry widget it added in Combobox widget of tkinter?
Is there any way when I enter text in Entry widget it added in Combobox widget of tkinter?

Time:11-05

When I add or edit a customer in Customer table, it does not appear in customer filed of Sales table, so I have to destroy the window and open it again manually or with refresh button. The refresh button also work 1 time, means when I add or edit another customer in Customer table, then click the refresh button just the window destroy. How to solve this problem without a refresh button means when I add or edit a customer in Customer table Immediately appear in customer filed of Sales table?

I add a customer name in Entry widget but it does not appear in Combobox

widget of tkinter. 
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import mysql.connector


root = Tk()
root.title('Car Store')
root.geometry('1600x860')

# Customer Functions
def update(rows):
    trv.delete(*trv.get_children())
    for dt in rows:
        trv.insert('', 'end', values=dt)


def get_row(event):
    item = trv.item(trv.focus())
    id_var.set(item['values'][0])
    name_var.set(item['values'][1])
    f_name_var.set(item['values'][2])
    last_name_var.set(item['values'][3])
    tazkera_no_var.set(item['values'][4])
    address_var.set(item['values'][5])
    mobile_no_var.set(item['values'][6])


def clean_data_list():
    ent_id.delete(0, END)
    ent_name.delete(0, END)
    ent_f_name.delete(0, END)
    ent_last_name.delete(0, END)
    ent_tazkera_no.delete(0, END)
    ent_address.delete(0, END)
    ent_mobile_no.delete(0, END)


def add_customer():
    if ent_name.get() == '':
        messagebox.showerror('Error!', 'Customer Name Field is required')
    else:
        con = mysql.connector.connect(user='nesarahmad',
                                      password='1114WE',
                                      host='127.0.0.1',
                                      database='carstore')
        my_cursor = con.cursor()

        query = 'USE carstore'
        my_cursor.execute(query)

        query = 'SELECT * FROM customer WHERE tazkera_num = %s'
        my_cursor.execute(query, (tazkera_no_var.get(),))
        row = my_cursor.fetchone()

        if row != None:
            messagebox.showerror(
                'Error!', 'Tazkera Number is Already exists, Try Another Tazkera Number')
        else:
            query = "INSERT INTO customer VALUES(%s, %s, %s, %s, %s, %s, %s)"
            values = ('null', name_var.get(), f_name_var.get(), last_name_var.get(
            ), tazkera_no_var.get(), address_var.get(), mobile_no_var.get())

            my_cursor.execute(query, values)
            con.commit()
            clear()
            con.close()
            clean_data_list()


def edit_customer():
    if messagebox.askyesno('Confirm Edit?', 'Are you shure you want to Edit this Customer'):
        con = mysql.connector.connect(user='nesarahmad',
                                      password='1114WE',
                                      host='127.0.0.1',
                                      database='carstore')
        my_cursor = con.cursor()

        customer_id = id_var.get()
        query = "UPDATE customer SET name=%s, f_name=%s, last_name=%s, tazkera_num=%s, address=%s, mobile_num=%s WHERE id="   customer_id
        values = (name_var.get(), f_name_var.get(), last_name_var.get(
        ), tazkera_no_var.get(), address_var.get(), mobile_no_var.get())
        my_cursor.execute(query, values)
        con.commit()
        clear()
        con.close()
        clean_data_list()
    else:
        return True


# Sales Functions
def update_sales_list(rows):
    trv_sales.delete(*trv_sales.get_children())
    for dt in rows:
        trv_sales.insert('', 'end', values=dt)


def sales_get_row(event):
    item = trv_sales.item(trv_sales.focus())
    id_var_sales.set(item['values'][0])
    cb_car_id.set(str(item['values'][1])   '-'   item['values'][3])
    cb_customer_id.set(str(item['values'][2])   '-'   item['values'][4])
    qty_var_sales.set(item['values'][5])
    sales_price_var_sales.set(item['values'][6])


def sales_clean_data_list():
    ent_id_sales.delete(0, END)
    cb_car_id_sales.set('')
    cb_customer_id_sales.set('')
    ent_qty_sales.delete(0, END)
    ent_sales_price_sales.delete(0, END)


def add_sales():
    if cb_car_id_sales.get() == '' or cb_customer_id_sales.get() == '' or ent_qty_sales.get() == '' or ent_sales_price_sales.get() == '':
        messagebox.showerror('Error!', 'All Fields are required')
    elif int(ent_qty_sales.get()) < 1 or int(ent_qty_sales.get()) > 1:
        messagebox.showerror('Error!', 'QTY must be 1')
    else:

        con = mysql.connector.connect(user='nesarahmad',
                                      password='1114WE',
                                      host='127.0.0.1',
                                      database='carstore')
        my_cursor = con.cursor()

        query = 'USE carstore'
        my_cursor.execute(query)

        query = "SELECT * FROM sales WHERE car_id = %s"
        my_cursor.execute(query, (cb_car_id.get().split('-')[0],))
        car_id = my_cursor.fetchone()
        if car_id != None:
            messagebox.showerror(
                'Error!', 'This car already solde, try another car')
        else:
            query = "SELECT COUNT(QTY) FROM car_inventory WHERE car_id = %s"
            my_cursor.execute(query, (cb_car_id.get().split('-')[0],))

            qty_car_inventory_check = my_cursor.fetchone()
            # print(qty_car_inventory_check)
            if qty_car_inventory_check[0] == 1:
                query = "INSERT INTO  sales VALUES(%s, %s, %s, %s, %s)"
                values = (
                    'null',
                    cb_car_id.get().split('-')[0],
                    cb_customer_id.get().split('-')[0],
                    qty_var_sales.get(),
                    sales_price_var_sales.get()
                )

                my_cursor.execute(query, values)

                # Update the QTY in Car Inventory
                query = "UPDATE car_inventory SET QTY = QTY - 1 WHERE car_id = %s"
                my_cursor.execute(query, (cb_car_id.get().split('-')[0],))

                con.commit()

                clear_sales()
                clear_car_inventory()
                con.close()
                sales_clean_data_list()
            else:
                messagebox.showerror(
                    '!Errot', 'There is no This Car in Car Inventory, Chose the Other Car')


def edit_sales():
    if messagebox.askyesno('Confirm Edit?', 'Are you shure you want to Edit this Sales'):
        if ent_qty_sales.get() == '' or ent_sales_price_sales.get() == '':
            messagebox.showerror('Error!', 'All Fields are required')
        elif int(ent_qty_sales.get()) < 1 or int(ent_qty_sales.get()) > 1:
            messagebox.showerror('Error!', 'QTY must be 1')
        else:
            con = mysql.connector.connect(user='nesarahmad',
                                          password='1114WE',
                                          host='127.0.0.1',
                                          database='carstore')
            my_cursor = con.cursor()

            id_sales = id_var_sales.get()
            query = "UPDATE sales SET car_id=%s, customer_id=%s, QTY=%s, sales_price=%s WHERE id="   id_sales
            values = (
                cb_car_id.get(),
                cb_customer_id.get(),
                qty_var_sales.get(),
                sales_price_var_sales.get(),
            )

            my_cursor.execute(query, values)
            con.commit()
            clear_sales()
            con.close()
            sales_clean_data_list()
    else:
        return True


def refresh():
    root.destroy()
    
    import CARSTORE


nb = ttk.Notebook(root)

frm_customer = Frame(nb, bg='firebrick1')

frm_wrapper1 = LabelFrame(frm_customer, text='Cusotmer List', pady=30)
frm_wrapper1.pack(fill='both', expand='yes', padx=40, pady=10)

frm_wrapper3 = LabelFrame(frm_customer, text='Customer Data', pady=30)
frm_wrapper3.pack(fill='both', expand='yes', padx=40, pady=(10, 50))

trv = ttk.Treeview(frm_wrapper1, selectmode='browse', columns=(
    1, 2, 3, 4, 5, 6, 7), show='headings')
trv.pack()

trv.heading(1, text='Customer ID')
trv.heading(2, text='Name')
trv.heading(3, text="Fateher's Name")
trv.heading(4, text='Last Name')
trv.heading(5, text='Tazkera no')
trv.heading(6, text='Address')
trv.heading(7, text='Mobile no')

# Hide Customer ID column
trv.column(1, stretch=NO, minwidth=0, width=0)

trv.bind('<Double 1>', get_row)

con = mysql.connector.connect(user='nesarahmad',
                              password='1114WE',
                              host='127.0.0.1',
                              database='carstore')
my_cursor = con.cursor()

query = 'USE carstore'
my_cursor.execute(query)

try:
    query = 'create table customer(id int auto_increment primary key, name varchar(50) not null, f_name varchar(50), last_name varchar(50), tazkera_num varchar(50) unique, address varchar(200), mobile_num varchar(13))'
    my_cursor.execute(query)
except:
    print('Same Tabel(s) exist.')

query = 'SELECT * FROM customer'
my_cursor.execute(query)
rows = my_cursor.fetchall()
update(rows)
con.close()


# Customer Data section
id_var = StringVar()
name_var = StringVar()
f_name_var = StringVar()
last_name_var = StringVar()
tazkera_no_var = StringVar()
address_var = StringVar()
mobile_no_var = StringVar()

lbl_id = Label(frm_wrapper3, text='Cutomer ID')
lbl_id.grid(row=0, column=0, sticky='w')
ent_id = Entry(frm_wrapper3, textvariable=id_var)
ent_id.grid(row=0, column=1)

# Hide the following 2 Label and Entry
lbl_id.grid_forget()
ent_id.grid_forget()

lbl_name = Label(frm_wrapper3, text='Name')
lbl_name.grid(row=1, column=0, sticky='w')
ent_name = Entry(frm_wrapper3, textvariable=name_var)
ent_name.grid(row=1, column=1)

lbl_f_name = Label(frm_wrapper3, text="Father's Name")
lbl_f_name.grid(row=2, column=0, sticky='w')
ent_f_name = Entry(frm_wrapper3, textvariable=f_name_var)
ent_f_name.grid(row=2, column=1)

lbl_last_name = Label(frm_wrapper3, text="Last Name")
lbl_last_name.grid(row=3, column=0, sticky='w')
ent_last_name = Entry(frm_wrapper3, textvariable=last_name_var)
ent_last_name.grid(row=3, column=1)

lbl_tazkera_no = Label(frm_wrapper3, text="Tazkera no")
lbl_tazkera_no.grid(row=4, column=0, sticky='w')
ent_tazkera_no = Entry(frm_wrapper3, textvariable=tazkera_no_var)
ent_tazkera_no.grid(row=4, column=1)

lbl_address = Label(frm_wrapper3, text="Address")
lbl_address.grid(row=5, column=0, sticky='w')
ent_address = Entry(frm_wrapper3, textvariable=address_var)
ent_address.grid(row=5, column=1)

lbl_mobile_no = Label(frm_wrapper3, text="Mobile no")
lbl_mobile_no.grid(row=6, column=0, sticky='w')
ent_mobile_no = Entry(frm_wrapper3, textvariable=mobile_no_var)
ent_mobile_no.grid(row=6, column=1)

btn_add_customer = Button(
    frm_wrapper3, text='Add Customer', width=15, bg='green', fg='white', activebackground='green', activeforeground='white', command=add_customer)
btn_add_customer.grid(row=7, column=0, pady=30)

btn_edit_customer = Button(
    frm_wrapper3, text='Edit Customer', width=15, bg='blue', fg='white', activebackground='blue', activeforeground='white', command=edit_customer)
btn_edit_customer.grid(row=7, column=1, pady=30)

frm_customer.pack(fill='both', expand='yes')
# End of Customer section


# Sales Section
frm_sales = Frame(nb, bg='firebrick1')

frm_sales_list = LabelFrame(
    frm_sales, text='Sales List', pady=30)
frm_sales_list.pack(fill='both', expand='yes', padx=40, pady=10)

frm_sales_data = LabelFrame(
    frm_sales, text='Sales Data', pady=30)
frm_sales_data.pack(fill='both', expand='yes', padx=40, pady=(10, 50))

trv_sales = ttk.Treeview(frm_sales_list, selectmode='browse', columns=(
    1, 2, 3, 4, 5, 6, 7), show='headings')
trv_sales.pack()

trv_sales.heading(1, text='Sales ID')
trv_sales.heading(2, text='Car ID')
trv_sales.heading(3, text="Customer ID")
trv_sales.heading(4, text="Car")
trv_sales.heading(5, text="Customer")
trv_sales.heading(6, text='QTY')
trv_sales.heading(7, text='Sales Price')

# Hide Sales ID, Car ID and Customer ID columns
trv_sales.column(1, stretch=NO, minwidth=0, width=0)
trv_sales.column(2, stretch=NO, minwidth=0, width=0)
trv_sales.column(3, stretch=NO, minwidth=0, width=0)
trv_sales.column(4, stretch=NO, minwidth=0, width=0)

trv_sales.bind('<Double 1>', sales_get_row)

con = mysql.connector.connect(user='nesarahmad',
                              password='1114WE',
                              host='127.0.0.1',
                              database='carstore')
my_cursor = con.cursor()

query = 'USE carstore'
my_cursor.execute(query)

try:
    query = 'CREATE TABLE sales(id int auto_increment primary key, car_id int NOT NULL UNIQUE, customer_id int, QTY int NOT NULL, sales_price decimal NOT NULL, FOREIGN KEY (car_id) REFERENCES car_inventory(car_id) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (customer_id) REFERENCES customer(id) ON DELETE CASCADE ON UPDATE CASCADE)'
    my_cursor.execute(query)
except:
    print('Same Tabel(s) exist.')

query = 'SELECT sales.id, car_inventory.car_id, customer.id, car_inventory.car_name, customer.name, sales.QTY, sales.sales_price FROM sales JOIN car_inventory ON car_inventory.car_id = sales.car_id JOIN customer ON customer.id = sales.customer_id'
my_cursor.execute(query)

rows = my_cursor.fetchall()

update_sales_list(rows)
con.close()


# Sales Data section
id_var_sales = StringVar()
cb_car_id = StringVar()
cb_customer_id = StringVar()
qty_var_sales = StringVar()
sales_price_var_sales = StringVar()

con = mysql.connector.connect(user='nesarahmad',
                              password='1114WE',
                              host='127.0.0.1',
                              database='carstore')
my_cursor = con.cursor()

customer_options_sales = []
query = 'SELECT id, name FROM customer'
my_cursor.execute(query)

customer_ids_names = my_cursor.fetchall()
for id_name in customer_ids_names:
    customer_options_sales.append(str(id_name[0])   '-'   id_name[1])

lbl_id_sales = Label(frm_sales_data, text='Sales ID')
lbl_id_sales.grid(row=0, column=0, sticky='w')
ent_id_sales = Entry(
    frm_sales_data, textvariable=id_var_sales)
ent_id_sales.grid(row=0, column=1)

# Hide the following 2 Label and Entry
lbl_id_sales.grid_forget()
ent_id_sales.grid_forget()

lbl_customer_id_sales = Label(frm_sales_data, text='Customer')
lbl_customer_id_sales.grid(row=2, column=0, sticky='w')
cb_customer_id_sales = ttk.Combobox(
    frm_sales_data, textvariable=cb_customer_id, state='readonly', width=17)
cb_customer_id_sales.grid(row=2, column=1)
cb_customer_id_sales['values'] = customer_options_sales

lbl_qty_sales = Label(frm_sales_data, text='QTY')
lbl_qty_sales.grid(row=3, column=0, sticky='w')
ent_qty_sales = Entry(
    frm_sales_data, textvariable=qty_var_sales)
ent_qty_sales.grid(row=3, column=1)

lbl_sales_price_sales = Label(frm_sales_data, text='Sales Price')
lbl_sales_price_sales.grid(row=4, column=0, sticky='w')
ent_sales_price_sales = Entry(
    frm_sales_data, textvariable=sales_price_var_sales)
ent_sales_price_sales.grid(row=4, column=1)

btn_add_sales = Button(
    frm_sales_data, text='Add ', width=15, bg='green', fg='white', activebackground='green', activeforeground='white', command=add_sales)
btn_add_sales.grid(row=5, column=0, pady=30)

btn_edit_sales = Button(
    frm_sales_data, text='Edit', width=15, bg='blue', fg='white', activebackground='blue', activeforeground='white', command=edit_sales)
btn_edit_sales.grid(row=5, column=1, pady=30)

btn_refresh_sales = Button(
    frm_sales_data, text='Refresh', width=15, bg='orange', fg='white', activebackground='orange', activeforeground='white', command=refresh)
btn_refresh_sales.grid(row=5, column=3, pady=30)

frm_sales.pack(fill='both', expand='yes')
# End of Sales Section

nb.pack(fill=BOTH, expand=True)

nb.add(frm_customer, text='Customer')
nb.add(frm_sales, text='Sales')


root.mainloop()

CodePudding user response:

I did not look further into your code as it is not reproducible and incomplete. You can achieve what you want by binding a callback to your entry widget (e.g. when hitting Return), and in that callback you first get the current values of your combobox, add the text from the entry to that list (= tuple) and then overwrite the values of your combobox with the newly created tuple. A minimal example would look like this:

from tkinter import Tk
from tkinter.ttk import Entry, Combobox

root = Tk()


def add_to_combobox(event):

    # replace values with new tuple from current values and text from entry
    my_combobox["values"] = my_combobox["values"]   (my_entry.get(), )

    # optional: select last item in combobox
    my_combobox.current(len(my_combobox["values"])-1)


my_entry = Entry(root)
my_entry.bind("<Return>", add_to_combobox)  # binds callback to widget when hitting return
my_entry.pack()

my_combobox = Combobox(root)
my_combobox.pack()
my_combobox["values"] = ("First default value", "Second default value")
my_combobox.config(state="readonly")
my_combobox.current(0)

root.mainloop()

CodePudding user response:

First add a function like cb_update_cus() and then call it in add_customer function after the con.commit()

def cb_update_cus():
    con = mysql.connector.connect(user='nesarahmad',
                                  password='1114WE',
                                  host='127.0.0.1',
                                  database='carstore')
    my_cursor = con.cursor()
    customer_options_sales = []
    query = 'SELECT id, name FROM customer'
    my_cursor.execute(query)

    customer_ids_names = my_cursor.fetchall()
    for id_name in customer_ids_names:
        customer_options_sales.append(str(id_name[0])   '-'   id_name[1])

    cb_customer_id_sales['values'] = customer_options_sales
  • Related