'''
آموزشگاه کامپیوتر راهکار تبریز
04135574231 - 09146585123
www.rahkar01.ir
پیشنهاد میکنیم سورس برنامه را خودتان چند بار صفر تا صد پیاده سازی کنید
تا برای آزمون عملی به مشکل نخورید
از حفظ کردن برنامه خودداری کنید و با مطالعه ویدئو و یادداشت برداری
برای خودتان منطق برنامه را درک کنید
درصورت نیاز به هرگونه توضیح تکمیلی یا آموزش بهتر با ما تماس بگیرید
'''

from tkinter import *
import sqlite3

conn = sqlite3.connect('tel.db')
curs = conn.cursor()
curs.execute('create table if not exists telbook (id integer primary key autoincrement , name text , phone text)')
global myid



def save():
    enam = e1.get();        etetl=e2.get()
    curs.execute('insert into telbook (name , phone) values(?,?)' , (enam , etetl))
    conn.commit()
    e1.delete(0,END);       e2.delete(0,END);     e1.focus_set()
    show()

def show():
    mylist.delete(0,END)
    curs.execute('select * from telbook')
    satr = curs.fetchall()
    for i in satr:
        mylist.insert(END , i)

def select(event):
    global myid
    index = mylist.curselection()
    neveshte = mylist.get(index)
    e1.delete(0,END);       e2.delete(0,END)
    e1.insert(0,neveshte[1]);           e2.insert(0 , neveshte[2])
    myid = neveshte[0]


def hazf():
    curs.execute(f'delete from telbook where id={myid}')
    conn.commit()
    print('hazf shod')
    show()

def virayesh():
    enam=e1.get();      etel=e2.get()
    curs.execute('update telbook set name=? , phone=? where id=?' , (enam, etel , myid))
    conn.commit()
    show()
    
def search():
    mylist.delete(0,END)
    curs.execute('select * from telbook where name=?' , (e3.get(),))
    satr = curs.fetchall()
    for i in satr:
        mylist.insert(END , i)

win = Tk()
win.geometry('500x500')
win.title('دفترچه تلفن ساده')

l1 = Label(win , text='نام').place(x=90 , y=30)
l2 = Label(win , text='شماره تماس').place(x=40 , y=60)

e1 = Entry(win);   e1.place(x=110 , y=30)
e2 = Entry(win);   e2.place(x=110 , y=60)

b1 = Button(win , text='ذخیره مخاطب' , command=save).place(x=20 , y =90 , width=90)
b2 = Button(win , text='حذف مخاطب' , command=hazf).place(x=120 , y =90 , width=90)
b3 = Button(win , text='ویرایش' , command=virayesh).place(x=220 , y =90 , width=90)
b4 = Button(win , text='نمایش همه' , command=show).place(x=320 , y =90 , width=90)

mylist = Listbox(win);     mylist.place(x=20 , y=120 , width=300 , height=300)
show()
mylist.bind('<<ListboxSelect>>' , select)

l3 = Label(win , text='جستجو').place(x=30 , y =450)
e3 = Entry(win);     e3.place(x=70,y=450)
b5 = Button(win , text='جستجو' , command=search).place(x=220 , y=450 , width=90)

mainloop()