застрял в Tkinter Toplevel - PullRequest
       7

застрял в Tkinter Toplevel

0 голосов
/ 20 сентября 2019

Я пытаюсь создать POS как мой проект Tkinter, но, кажется, что-то не так, основная программа работает отлично, но когда я пытаюсь создать Toplevel: Add Stock, используйте тот же метонд, что и в основной программе., но, кажется, он застрял в списке общей суммы и расчета общей стоимости и показать ошибку

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Rocklee\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/Rocklee/PycharmProjects/POS/POS Main.py", line 420, in addstock_enter_key
    add_stock_open_file('VL_price.xls')
  File "C:/Users/Rocklee/PycharmProjects/POS/POS Main.py", line 359, in add_stock_open_file
    addstock_total_count()  # display the total items and total price
  File "C:/Users/Rocklee/PycharmProjects/POS/POS Main.py", line 376, in addstock_total_count
    addstock_lable_itemsandprice.grid_forget()
NameError: name 'addstock_lable_itemsandprice' is not defined

Вот код:

from tkinter import *
import PIL
import time
from tkinter import ttk
import xlrd
from xlutils.copy import copy
from tkinter import messagebox

root = Tk()
root.title("Vitamin L POS")
root.iconbitmap('d:/123.ico')
root.minsize(width=300, height=400)
root.resizable(width=1000, height=1000)

# clock
time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

def clock():
    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    if T_timer != '':
        T_timer.config(text=time_now, font='times 15')
    root.after(100, clock)

# clock position
T_timer = Label(root, text=time_now, width=55, anchor=W, )
clock()

# receipt number
wb = xlrd.open_workbook("dailysalesrecord.xls")
ws = wb.sheet_by_index(0)
receipt_number = int(ws.cell_value(-1, 0)) + 1  # the number need to update from last receipt
lable_receipt = Label(root, text=' Receipt Number: ' + str(receipt_number), font='times 15', width=55, anchor=W)

# update the receipt_number and label_receipt after payment and listbox
def update_receipt():
    global receipt_number
    global label_receipt
    zero = []
    if product_list == []:
        messagebox.showwarning("empty list", "Empty List")
    else:
        lable_receipt.grid_forget()
        wb1 = xlrd.open_workbook("dailysalesrecord.xls")
        ws1 = wb1.sheet_by_index(0)
        receipt_number = int(ws1.cell_value(-1, 0)) + 1
        label_receipt = Label(root, text=' Receipt Number: ' + str(receipt_number), font='times 15', width=55,
                              anchor=W)
        label_receipt.grid(row=1, column=0)
        print('receipt update complete')
        clear_listboxandproductlist()

def clear_listboxandproductlist():
    for ele in listBox.get_children():
        listBox.delete(ele)
    total_item = 0
    total_price = 0
    total_itemandprice = str('Total Items ' + str(total_item) + '  Total HKD' + str(total_price))
    lable_itemsandprice = Label(root, text=total_itemandprice, width=53, bd=10, anchor=E, font='Calibri 15')
    lable_itemsandprice.grid(row=4, column=0)
    Cash.place(x=20, y=550, height=50, width=50)
    visa.place(x=70, y=550, height=50, width=50)
    master.place(x=120, y=550, height=50, width=50)
    Daisy.place(x=170, y=550, height=50, width=50)

# store in daislysalesrecord
def receipt_store(store_list):
    now = int(time.time())
    timestruct = time.localtime(now)
    date_now = time.strftime("%Y-%m-%d", timestruct)
    time_now = time.strftime("%H:%M:%S", timestruct)
    rb1 = xlrd.open_workbook('dailysalesrecord.xls')
    rs1 = rb1.sheet_by_index(0)
    receipt_number_for_store_list = int(rs1.cell_value(-1, 0)) + 1
    wbn = copy(rb1)
    wsn = wbn.get_sheet(0)
    row_add = -1
    last_row = rs1.nrows
    for ele in store_list:
        row_add += 1
        wsn.write(last_row + row_add, 0, receipt_number_for_store_list)
        wsn.write(last_row + row_add, 1, date_now)
        wsn.write(last_row + row_add, 2, time_now)
        wsn.write(last_row + row_add, 3, ele[0])
        wsn.write(last_row + row_add, 4, ele[1])
        wsn.write(last_row + row_add, 5, ele[2])
        wsn.write(last_row + row_add, 6, ele[3])
        wsn.write(last_row + row_add, 7, ele[4])
        if ele == store_list[-1]:
            wsn.write(last_row + row_add, 8, total_price)
            wsn.write(last_row + row_add, 9, payment)
    wbn.save('dailysalesrecord.xls')
    print(product_list)
    update_receipt()
    product_list_empty()
    print(product_list)

def product_list_empty():
    global product_list
    product_list = []

product_list_empty()

# barcode set up
def open_file(path):
    wb_openfile = xlrd.open_workbook(path)
    sheet = wb_openfile.sheet_by_index(0)
    enter_barcode = barcode_scaner.get()
    global product_name_value
    global product_price_value
    global product_quantity
    global subtotal
    for n in range(sheet.nrows):
        barcode_value = sheet.cell_value(n, 0)
        product_name_value = sheet.cell_value(n, 1)
        product_price_value = sheet.cell_value(n, 3)
        product_quantity = 1
        subtotal = int(product_price_value) * product_quantity
        if barcode_value == float(enter_barcode):
            for ele in product_list:
                if ele[1] == product_name_value:
                    product_quantity = ele[3] + 1
                    subtotal = int(product_price_value) * product_quantity
                    product_list.remove(ele)
                    print('addquantity')
                else:
                    product_quantity = 1
                    subtotal = int(product_price_value) * product_quantity
            product_list.append(
                [enter_barcode, product_name_value, product_price_value, product_quantity, subtotal])
            # print(product_list)
            # print(str(enter_barcode) + product_name_value + str(product_quantity) + str(product_price_value) + str(subtotal))
            # add_item = [barcode_value, product_name_value, product_quantity, product_price_value, subtotal ]
    for i in listBox.get_children():
        print(i)
        listBox.delete(i)
    show2()  # to put on listbox
    total_count()  # display the total items and total price

def enter_key(self):  # for barcode scanner
    entered_barcode = str(barcode_scaner.get())
    open_file('VL_price.xls')

    barcode_scaner.delete(0, END)

# barcode
barcode_scaner = Entry(root, width=46, font='time 20')
barcode_scaner.bind('<Return>', enter_key)

# display_list contains barcode, product name, price, quantity and subtotal
def show2():
    print('show2')
    for i, (barcode, productname, price, quantity, subtotal) in enumerate(product_list, start=1):
        listBox.insert("", "end", values=(i, barcode, productname, price, quantity, subtotal))

# def show():
# listBox = [['Jim', '0.33'], ['Dave', '0.67'], ['James', '0.67'], ['Eden', '0.5']]
#
#  for i, (name, score) in enumerate(listBox, start=1):
#      listBox.insert("", "end", values=(i, name, score))

# create Treeview with 6 columns
cols = ('Item', 'Barcode', 'Product Name', 'Unit Price', 'Quantity', 'Subtotal')
style = ttk.Style()
style.configure('mystyle.Treeview', font=('Calibri', 15, 'bold'))
listBox = ttk.Treeview(root, columns=cols, show='headings', height=20, style="mystyle.Treeview")
vsb = ttk.Scrollbar(root, orient="vertical", command=listBox.yview)
vsb.place(x=622, y=95, height=400 + 20)

# set column headings
listBox.heading('Item', text="Item")
listBox.column('Item', width=40)  # columnwidth
listBox.heading('Barcode', text='Barcode')
listBox.column('Barcode', width=150)
listBox.heading('Product Name', text='Product Name')
listBox.column('Product Name', width=250)
listBox.heading('Unit Price', text='Unit Price')
listBox.column('Unit Price', width=60)
listBox.heading('Quantity', text='Quantity')
listBox.column('Quantity', width=60)
listBox.heading('Subtotal', text='Subtotal')
listBox.column('Subtotal', width=60)

# show()
# place to store the scanned list value

# total items
def total_count():
    global lable_itemsandprice
    global total_price
    lable_itemsandprice.grid_forget()
    total_item = 0
    total_price = 0
    for ele in product_list:
        total_item += ele[3]
        total_price += ele[4]
    total_itemandprice = str('Total Items ' + str(total_item) + '  Total HKD' + str(total_price))
    lable_itemsandprice = Label(root, text=total_itemandprice, width=53, bd=10, anchor=E, font='Calibri 15')
    lable_itemsandprice.grid(row=4, column=0)

total_item = 0
total_price = 0
total_itemandprice = str('Total Items ' + str(total_item) + '  Total HKD ' + str(total_price))
lable_itemsandprice = Label(root, text=total_itemandprice, width=53, bd=10, anchor=E, font='Calibri 15')

def payment_change(pay):
    global payment
    payment = pay
    if product_list != []:
        if payment == 'Cash':
            messagebox.showinfo("Cash", "Total" + str(total_price) + '\n' + 'Payment Cash')
        elif payment == 'Visa':
            messagebox.showinfo("Visa", "Total" + str(total_price) + '\n' + 'Payment Visa')
        elif payment == 'Master':
            messagebox.showinfo("Master", "Total" + str(total_price) + '\n' + 'Payment Master')
        elif payment == 'Daisy':
            messagebox.showinfo("Daisy", "Total" + str(total_price) + '\n' + 'Payment Daisy')

    print(payment)
    receipt_store(product_list)

item_name_selected = ''

def selected_item(event):
    global item_name_selected
    row_selected = event.widget.focus()
    values = event.widget.item(row_selected)['values']
    item_name_selected = values[1]
    print('selected item for delete ' + str(item_name_selected))

def delete_item(event2):
    # print(event2)
    # print('state of product list in delete item stage' + str(product_list))
    if product_list == []:
        messagebox.showwarning('The list is empty', 'The list is empty')
        # print('delete list error')
    elif not item_name_selected:
        messagebox.showwarning('Select one item to delete', 'Select One Item To Delete')
    for ele in product_list:
        if int(ele[0]) == event2:
            product_list.remove(ele)
            # print('deleted'+ str(ele))
    for i in listBox.get_children():
        # print(' show in delete listsboxi', product_list)
        listBox.delete(i)
    show2()  # to put on listbox
    total_count()  # display the total items and total price

qty = IntVar()
qty_for_change = Entry(root, width=2, font='times 29', textvariable=qty)

def change_qty(event3):
    if product_list == []:
        messagebox.showwarning('The list is empty', 'The list is empty')
        # print('delete list error')
    elif not item_name_selected:
        messagebox.showwarning('Select one item to change', 'Select One Item To change')
    for ele in product_list:
        if int(ele[0]) == event3:
            new_qty = qty.get()
            ele[3] = new_qty
            ele[4] = int(new_qty * ele[2])
            print('qty change ', product_list)
            # print('deleted'+ str(ele))

    for i in listBox.get_children():
        # print(' show in delete listsboxi', product_list)
        listBox.delete(i)
    show2()  # to put on listbox
    total_count()  # display the total items and total price

listBox.bind('<<TreeviewSelect>>', selected_item)
delete_button = Button(root, text='Delete' + '\nItem', command=lambda: delete_item(item_name_selected), bg='red')
change_qty_button = Button(root, text='Change \n QTY', command=lambda: change_qty(item_name_selected), bg='green')

payment = ''
# Display
# paymentbutton
Cash = Button(root, text="cash", command=lambda: payment_change('Cash'))
visa = Button(root, text='Visa', command=lambda: payment_change('Visa'))
master = Button(root, text='Master', command=lambda: payment_change('Master'))
Daisy = Button(root, text='Daisy', command=lambda: payment_change('Daisy'))

# Payment_button = Button(root, text='Pay', command=lambda: update_receipt())

def add_stock_frame_func():
    add_stock_frame = Toplevel(root)
    add_stock_frame.geometry('620x600')
    add_stock_frame.title('Add Stock')
    add_stock_frame.iconbitmap('d:/123.ico')

    def addtock_product_list_empty():
        global addstock_product_list
        addstock_product_list = []

    addtock_product_list_empty()

    def add_stock_open_file(path2):
        addstock_wb_openfile = xlrd.open_workbook(path2)
        addstock_sheet = addstock_wb_openfile.sheet_by_index(0)
        addstock_enter_barcode = addstock_barcode_scaner.get()
        addstock_wb_openfile = xlrd.open_workbook(path2)
        addstock_sheet = addstock_wb_openfile.sheet_by_index(0)
        addstock_enter_barcode = addstock_barcode_scaner.get()
        global addstock_product_name_value
        global addstock_product_price_value
        global addstock_product_quantity
        global addstock_subtotal
        global addstock_product_list
        for n in range(addstock_sheet.nrows):
            addstock_barcode_value = addstock_sheet.cell_value(n, 0)
            addstock_product_name_value = addstock_sheet.cell_value(n, 1)
            addstock_product_price_value = addstock_sheet.cell_value(n, 3)
            addstock_product_quantity = 1
            addstock_subtotal = int(addstock_product_price_value) * addstock_product_quantity
            if addstock_barcode_value == float(addstock_enter_barcode):
                for ele in addstock_product_list:
                    print(ele)
                    if ele[1] == addstock_product_name_value:
                        addstock_product_quantity = ele[3] + 1
                        addstock_subtotal = int(addstock_product_price_value) * addstock_product_quantity
                        addstock_product_list.remove(ele)
                        print('addstock_addquantity')
                    else:
                        addstock_product_quantity = 1
                        addstock_subtotal = int(addstock_product_price_value) * addstock_product_quantity
                addstock_product_list.append(
                    [addstock_enter_barcode, addstock_product_name_value, addstock_product_price_value,
                     addstock_product_quantity, addstock_subtotal])
                print(product_list)
                # print(str(enter_barcode) + product_name_value + str(product_quantity) + str(product_price_value) + str(subtotal))
                # add_item = [barcode_value, product_name_value, product_quantity, product_price_value, subtotal ]
        for i in listBox2.get_children():
            print(i)
            listBox2.delete(i)
        addstock_show2()  # to put on listbox
        addstock_total_count()  # display the total items and total price

    def addstock_show2():
        print('addstock_show2')
        for i, (barcode, productname, price, quantity, subtotal) in enumerate(addstock_product_list, start=1):
            listBox2.insert("", "end", values=(i, barcode, productname, price, quantity, subtotal))

    addstock_total_item = 0
    addstock_total_price = 0
    addstock_total_itemandprice = str(
        'Total Items ' + str(addstock_total_item) + '  Total HKD ' + str(addstock_total_price))
    addstock_lable_itemsandprice = Label(add_stock_frame, text=addstock_total_itemandprice, width=53, bd=10,
                                         anchor=E,
                                         font='Calibri 15')

    def addstock_total_count():
        global addstock_lable_itemsandprice
        global addstock_total_price
        addstock_lable_itemsandprice.grid_forget()
        addstock_total_item = 0
        addstock_total_price = 0
        for ele in addstock_product_list:
            addstock_total_item += ele[3]
            addstock_total_price += ele[4]
        addstock_total_itemandprice = str(
            'Total Items ' + str(addstock_total_item) + '  Total HKD' + str(addstock_total_price))
        addstock_lable_itemsandprice = Label(addstock_frame, text=addstock_total_itemandprice, width=53, bd=10,
                                             anchor=E,
                                             font='Calibri 15')
        addstock_lable_itemsandprice.grid(row=4, column=0)

    cols2 = ('Item', 'Barcode', 'Product Name', 'Unit Price', 'Quantity', 'Subtotal')
    style2 = ttk.Style()
    style2.configure('mystyle2.Treeview', font=('Calibri', 15, 'bold'))
    listBox2 = ttk.Treeview(add_stock_frame, columns=cols, show='headings', height=20, style="mystyle2.Treeview")
    # set column headings
    listBox2.heading('Item', text="Item")
    listBox2.column('Item', width=40)  # columnwidth
    listBox2.heading('Barcode', text='Barcode')
    listBox2.column('Barcode', width=150)
    listBox2.heading('Product Name', text='Product Name')
    listBox2.column('Product Name', width=250)
    listBox2.heading('Unit Price', text='Unit Price')
    listBox2.column('Unit Price', width=60)
    listBox2.heading('Quantity', text='Quantity')
    listBox2.column('Quantity', width=60)
    listBox2.heading('Subtotal', text='Subtotal')
    listBox2.column('Subtotal', width=60)
    # show()
    listBox2.grid(row=3, column=0, columnspan=6)

    def addstock_delete_item():
        pass

    def addstock_change_qty():
        pass

    def addstock_confirm():
        pass

    def addstock_enter_key(self):  # for barcode scanner
        addstock_entered_barcode = str(addstock_barcode_scaner.get())
        add_stock_open_file('VL_price.xls')
        delete_barcode_scanner()

    def delete_barcode_scanner():
        addstock_barcode_scaner.delete('0', END)

    addstock_barcode_scaner = Entry(add_stock_frame, width=46, font='time 20')
    addstock_barcode_scaner.bind('<Return>', addstock_enter_key)
    # display

    addstock_delete_button = Button(add_stock_frame, text='Delete' + '\nItem',
                                    command=lambda: addstock_delete_item(addstock_item_name_selected), bg='red')
    addstock_change_qty_button = Button(add_stock_frame, text='Change \n QTY',
                                        command=lambda: addstock_change_qty(addstock_item_name_selected),
                                        bg='green')
    addstock_delete_button.place(x=20, y=500, height=50, width=50)
    addstock_change_qty_button.place(x=70, y=500, height=50, width=50)
    addstock_confirm_button = Button(add_stock_frame, text='Confirm', command=lambda: addstock_confirm)
    addstock_confirm_button.place(x=220, y=500, height=50, width=50)
    addstock_barcode_scaner.grid(row=2, column=0, pady=10)
    listBox2.grid(row=3, column=0, columnspan=6)
    addstock_lable_itemsandprice.grid(row=4, column=0)

stockin_button = Button(root, text="Add\nStock", command=lambda: add_stock_frame_func())

emptylabel = Label(root, pady=20)
emptylabel2 = Label(root, padx=50)
T_timer.grid(row=0, column=0, columnspan=6)
lable_receipt.grid(row=1, column=0)
barcode_scaner.grid(row=2, column=0, pady=10)
listBox.grid(row=3, column=0, columnspan=6)
lable_itemsandprice.grid(row=4, column=0)
Cash.place(x=20, y=580, height=50, width=50)
visa.place(x=70, y=580, height=50, width=50)
master.place(x=120, y=580, height=50, width=50)
Daisy.place(x=170, y=580, height=50, width=50)
delete_button.place(x=270, y=580, height=50, width=50)
change_qty_button.place(x=320, y=580, height=50, width=50)
qty_for_change.place(x=370, y=580)
stockin_button.place(x=520, y=580, height=50, width=50)
emptylabel.grid(row=5, column=1, columnspan=2)
# emptylabel2.grid(row= 5, column = 2)

# Payment_button.place(x=20, y=560, height=50, width=200)

root.mainloop()
...