Amazing-Python-Scripts

Форк
0
259 строк · 6.9 Кб
1
'''
2
importing all the required libraries
3
'''
4
import sqlite3
5
from sqlite3 import Error
6
from tkinter import *
7
import tkinter.messagebox
8
root = Tk()
9
root.geometry('600x370')
10
list_of_names = []
11
root.title('AddressBook')
12
Name = StringVar()
13
Number = StringVar()
14

15
""" creating a database connection to the SQLite database
16
    specified by db_file
17
    return: Connection object or None
18
    """
19

20

21
def create_connection(db_file):
22
    conn = None
23
    try:
24
        conn = sqlite3.connect(db_file)
25
        r_set = conn.execute('''SELECT * from tasks''')
26
        for student in r_set:
27
            list_of_names.append(student[1])
28
        return conn
29
    except Error as e:
30
        print(e)
31
    return conn
32

33

34
""" create a table from the create_table_sql statement
35
    conn: Connection object
36
    create_table_sql: a CREATE TABLE statement
37
    """
38

39

40
def create_table(conn, create_table_sql):
41
    try:
42
        c = conn.cursor()
43
        c.execute(create_table_sql)
44
    except Error as e:
45
        print(e)
46
    return
47

48

49
'''
50
displaying added/deleted message
51
'''
52

53

54
def onClickAdded():
55
    tkinter.messagebox.showinfo(" ", Name.get()+" got added")
56

57

58
def onClickDeleted():
59
    tkinter.messagebox.showinfo(" ", Name.get()+" got deleted")
60

61

62
""" Create a new task (ie creating new row) for the given Name  taking care of all conditions such as  Name,phone no
63
cannot be empty ,phone no should be 10 digits and also if  Name already exist,then it cannot be inerted
64
"""
65

66

67
def create_task():
68
    sql = ''' INSERT INTO tasks(name,status_id)
69
              VALUES(?,?) '''
70
    if (Name.get() not in list_of_names):
71

72
        if ((Name.get() == '') | (Number.get() == '') | (len(Number.get()) != 10)):
73
            top = Toplevel(root)
74
            top.geometry('180x100')
75
            if ((Number.get() == '') | (len(Number.get()) != 10)):
76
                myLabel = Label(top, text="Phone no should be 10  digits\n")
77
            else:
78
                myLabel = Label(top, text="NAME IS EMPTY\n")
79
            myLabel.pack()
80
            mySubmitButton = Button(top, text=' Back ', command=top.destroy)
81
            mySubmitButton.pack()
82
            return
83
        onClickAdded()
84
        cur = conn.cursor()
85
        cur.execute(sql, (Name.get(), Number.get()))
86
        conn.commit()
87
        return cur.lastrowid
88
    else:
89
        top = Toplevel(root)
90
        top.geometry('180x100')
91
        if (Name.get() == ''):
92
            myLabel = Label(top, text="NAME IS EMPTY\n")
93
        elif ((Number.get() == '') | (len(Number.get()) != 10)):
94
            myLabel = Label(top, text="Phone no should be 10  digits\n")
95
        else:
96
            myLabel = Label(top, text=Name.get()+"  Already Exist\n")
97
        myLabel.pack()
98
        mySubmitButton = Button(top, text=' Back ', command=top.destroy)
99
        mySubmitButton.pack()
100

101

102
"""
103
Query tasks by Name, if name not found then it gives a warning saying "NOT Found"
104
"""
105

106

107
def select_task_by_name():
108
    cur = conn.cursor()
109
    cur.execute("SELECT * FROM tasks WHERE name=?", (Name.get(),))
110
    rows = cur.fetchall()
111
    if (len(rows) == 0):
112
        inputDialog = MyDialog(root)
113
        root.wait_window(inputDialog.top)
114
    else:
115
        Number.set(rows[0][2])
116

117

118
"""
119
Editing phone no, if name not found then it gives a warning saying "NOT Found"
120
"""
121

122

123
def update_task():
124
    """
125
    update priority, begin_date, and end date of a task
126
    :param conn:
127
    :param task:
128
    :return: project id
129
    """
130
    sql = ''' UPDATE tasks
131
              SET status_id = ?   
132
              WHERE name = ?'''
133
    if ((Name.get() not in list_of_names) | (Name.get() == '')):
134
        inputDialog = MyDialog(root)
135
        root.wait_window(inputDialog.top)
136
        return
137
    cur = conn.cursor()
138
    cur.execute(sql, (Number.get(), Name.get()))
139
    conn.commit()
140

141

142
"""
143
Delete a task by name.if not found ,gives a warning!!!
144
"""
145

146

147
def delete_task():
148
    if ((Name.get() not in list_of_names) | (Name.get() == '')):
149
        inputDialog = MyDialog(root)
150
        root.wait_window(inputDialog.top)
151
        return
152
    onClickDeleted()
153
    sql = 'DELETE FROM tasks WHERE name=?'
154
    cur = conn.cursor()
155
    cur.execute(sql, (Name.get(),))
156
    conn.commit()
157

158

159
"""
160
Get all rows in the tasks table
161
"""
162

163

164
def select_all_tasks():
165
    r_set = conn.execute('''SELECT * from tasks''')
166
    i = 0
167
    j = 0
168
    top = Toplevel(root)
169
    for student in r_set:
170
        list_of_names.append(student[1])
171
        for j in range(len(student)):
172
            e = Entry(top, width=11, fg='Gray20')
173
            e.grid(row=i, column=j)
174
            e.insert(END, student[j])
175
        i = i+1
176
    okButton = Button(top, text=' ok ', command=top.destroy)
177
    if (j == 0):
178
        j = 1
179
    okButton.grid(row=i+3, column=j-1)
180

181

182
'''
183
Getting the path of database and defining the table to be created
184
'''
185
database = r"./Address-Book/addressbook.db"
186
sql_create_tasks_table = """CREATE TABLE IF NOT EXISTS tasks (
187
                                    id integer PRIMARY KEY,
188
                                    name text NOT NULL,
189
                                    status_id integer NOT NULL
190
                                  
191
                                );"""
192

193
'''
194
Creating connection and gives error message if connection failed
195
'''
196
conn = create_connection(database)
197
if conn is not None:
198
    create_table(conn, sql_create_tasks_table)
199
else:
200
    print("Error! cannot create the database connection.")
201

202
'''
203
creating dialog box for warnings!
204
'''
205

206

207
class MyDialog:
208
    def __init__(self, parent):
209
        top = self.top = Toplevel(parent)
210
        self.myLabel = Label(top, text=Name.get().upper()+" NOT FOUND!")
211
        self.myLabel.pack()
212
        self.mySubmitButton = Button(top, text='Exit', command=self.send)
213
        self.mySubmitButton.pack()
214

215
    def send(self):
216
        self.top.destroy()
217

218

219
'''
220
Exiting from the application
221
'''
222

223

224
def EXIT():
225
    root.destroy()
226

227

228
'''
229
Resetting Name and phone no field
230
'''
231

232

233
def RESET():
234
    Name.set('')
235
    Number.set('')
236

237

238
'''
239
Creating UI for whole application
240
'''
241
Label(root, text='NAME', font='Times 15 bold').place(x=130, y=20)
242
Entry(root, textvariable=Name, width=42).place(x=200, y=25)
243
Label(root, text='PHONE NO ', font='Times 15 bold').place(x=130, y=70)
244
Entry(root, textvariable=Number, width=35).place(x=242, y=73)
245
Button(root, text=" ADD", font='Times 14 bold', bg='dark gray',
246
       command=create_task, width=8).place(x=130, y=110)
247
Button(root, text="EDIT", font='Times 14 bold', bg='dark gray',
248
       command=update_task, width=8).place(x=260, y=108)
249
Button(root, text="DELETE", font='Times 14 bold', bg='dark gray',
250
       command=delete_task, width=8).place(x=390, y=107.5)
251
Button(root, text="VIEW ALL", font='Times 14 bold', bg='dark gray',
252
       command=select_all_tasks, width=12).place(x=160, y=191)
253
Button(root, text="VIEW BY NAME", font='Times 14 bold', bg='dark gray',
254
       command=select_task_by_name, width=13).place(x=330, y=190)
255
Button(root, text="EXIT", font='Times 14 bold', bg='dark gray',
256
       command=EXIT, width=8).place(x=200, y=280)
257
Button(root, text="RESET", font='Times 14 bold', bg='dark gray',
258
       command=RESET, width=8).place(x=320, y=280)
259
root.mainloop()
260

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.