Задание
С помощью языка Python и библиотеки Tkinter реализовать простое приложение для проектного бюро. Приложение должно позволять вести учет проектов, их статусах и стоимости.
Функционал программы
- Добавление проектов
- Редактирование проекта
- Удаление проекта
- поиск записей в БД
Фрагмент программного кода
import tkinter as tk
from tkinter import ttk
import sqlite3
# Класс Main
def open_update_dialog():
Update()
class Main(tk.Frame):
def __init__(self, root):
super().__init__(root)
self.tree = None
self.refresh_img = tk.PhotoImage(file='refresh.png')
self.search_img = tk.PhotoImage(file='search.png')
self.delete_img = tk.PhotoImage(file='delete.png')
self.update_img = tk.PhotoImage(file='edit.png')
self.add_img = tk.PhotoImage(file='add.png')
self.init_main()
self.db = db
self.view_records()
# Главное окно
def init_main(self):
title_label = tk.Label(root, text="Проектное Бюро", font=("Arial", 15, "bold"),
border=12, relief=tk.GROOVE, bg="black", foreground="yellow")
title_label.pack(side=tk.TOP, fill=tk.X)
toolbar = tk.Frame(bg='blueviolet', bd=2)
toolbar.pack(side=tk.TOP, fill=tk.X)
btn_open_dialog = tk.Button(toolbar, text='Добавить проект', command=self.open_dialog, bg='blueviolet',
bd=0, compound=tk.TOP, image=self.add_img)
btn_open_dialog.pack(side=tk.LEFT)
btn_edit_dialog = tk.Button(toolbar, text='Редактировать', bg='blueviolet', bd=0, image=self.update_img,
compound=tk.TOP, command=open_update_dialog)
btn_edit_dialog.pack(side=tk.LEFT)
btn_delete_dialog = tk.Button(toolbar, text='Удалить', bg='blueviolet', bd=0, image=self.delete_img,
compound=tk.TOP, command=self.delete_records)
btn_delete_dialog.pack(side=tk.LEFT)
btn_search = tk.Button(toolbar, text='Поиск', bg='blueviolet', bd=0, image=self.search_img,
compound=tk.TOP, command=self.open_search_dialog)
btn_search.pack(side=tk.LEFT)
btn_refresh = tk.Button(toolbar, text='Обновить', bg='blueviolet', bd=0, image=self.refresh_img,
compound=tk.TOP, command=self.view_records)
btn_refresh.pack(side=tk.LEFT)
columns = ('ID', 'project', 'status', 'price')
self.tree = ttk.Treeview(self, columns=columns, height=15, show='headings')
self.tree.column('ID', width=30, anchor=tk.CENTER)
self.tree.column('project', width=365, anchor=tk.CENTER)
self.tree.column('status', width=120, anchor=tk.CENTER)
self.tree.column('price', width=110, anchor=tk.CENTER)
self.tree.heading('ID', text='ID')
self.tree.heading('project', text='Проект')
self.tree.heading('status', text='Статус')
self.tree.heading('price', text='Стоимость')
self.tree.pack(side=tk.LEFT)
scroll = tk.Scrollbar(self, command=self.tree.yview)
scroll.pack(side=tk.LEFT, fill=tk.Y)
self.tree.configure(yscrollcommand=scroll.set)
# Добавление данных
def records(self, project, status, price):
self.db.insert_data(project, status, price)
self.view_records()
# Обновление данных
def update_record(self, project, status, price):
self.db.c.execute('''UPDATE bureau SET project=?, status=?, price=? WHERE ID=?''',
(project, status, price, self.tree.set(self.tree.selection()[0], '#1')))
self.db.conn.commit()
self.view_records()
# Вывод данных
def view_records(self):
self.db.c.execute('''SELECT * FROM bureau''')
[self.tree.delete(i) for i in self.tree.get_children()]
[self.tree.insert('', 'end', values=row) for row in self.db.c.fetchall()]
# Удаление данных
def delete_records(self):
for selection_item in self.tree.selection():
self.db.c.execute('''DELETE FROM bureau WHERE id=? ''', (self.tree.set(selection_item, '#1'),))
self.db.conn.commit()
self.view_records()
# Поиск данных
def search_records(self, project):
project = ('%' + project + '%',)
self.db.c.execute('''SELECT * FROM bureau WHERE project LIKE ?''', project)
[self.tree.delete(i) for i in self.tree.get_children()]
[self.tree.insert('', 'end', values=row) for row in self.db.c.fetchall()]
# Открытие дочернего окна
@staticmethod
def open_dialog():
Child()
@staticmethod
def open_search_dialog():
Search()
# Дочернее окно
class Child(tk.Toplevel):
def __init__(self):
super().__init__(root)
self.btn_ok = ttk.Button(self, text='Добавить')
self.combobox = ttk.Combobox(self, values=[u'Открыт', u'Выполняется', u'Закрыт', u'Отменен'])
self.entry_price = ttk.Entry(self)
self.entry_project = ttk.Entry(self)
self.init_child()
self.view = app
def init_child(self):
self.title('Добавить проект')
self.geometry('400x220+400+300')
self.resizable(False, False)
label_project = tk.Label(self, text='Проект')
label_project.place(x=50, y=50)
label_select = tk.Label(self, text='Статус')
label_select.place(x=50, y=80)
label_price = tk.Label(self, text='Стоимость')
label_price.place(x=50, y=110)
self.entry_project.place(x=200, y=50)
self.entry_price.place(x=200, y=110)
self.combobox.current(0)
self.combobox.place(x=200, y=80)
btn_cancel = ttk.Button(self, text='Закрыть', command=self.destroy)
btn_cancel.place(x=300, y=150)
self.btn_ok.place(x=220, y=150)
self.btn_ok.bind('<Button-1>', lambda event: self.view.records(self.entry_project.get(),
self.combobox.get(),
self.entry_price.get()))
self.grab_set()
self.focus_set()
# Класс обновления унаследованный от дочернего окна
class Update(Child):
def __init__(self):
super().__init__()
self.init_edit()
self.view = app
self.db = db
self.default_data()
def init_edit(self):
self.title('Редактировать проект')
btn_edit = ttk.Button(self, text='Редактировать')
btn_edit.place(x=205, y=150)
btn_edit.bind('<Button-1>', lambda event: self.view.update_record(self.entry_project.get(),
self.combobox.get(),
self.entry_price.get()))
self.btn_ok.destroy()
def default_data(self):
self.db.c.execute('''SELECT * FROM bureau WHERE id=?''',
(self.view.tree.set(self.view.tree.selection()[0], '#1'),))
row = self.db.c.fetchone()
self.entry_project.insert(0, row[1])
if row[2] != 'Открыт':
self.combobox.current(1)
self.entry_price.insert(0, row[3])
# Поиск по наименованию
class Search(tk.Toplevel):
def __init__(self):
super().__init__()
self.entry_search = ttk.Entry(self)
self.init_search()
self.view = app
def init_search(self):
self.title('Поиск')
self.geometry('300x100+400+300')
self.resizable(False, False)
label_search = tk.Label(self, text='Поиск')
label_search.place(x=50, y=20)
self.entry_search.place(x=105, y=20, width=150)
btn_cancel = ttk.Button(self, text='Закрыть', command=self.destroy)
btn_cancel.place(x=185, y=50)
btn_search = ttk.Button(self, text='Поиск')
btn_search.place(x=105, y=50)
btn_search.bind('<Button-1>', lambda event: self.view.search_records(self.entry_search.get()))
btn_search.bind('<Button-1>', lambda event: self.destroy(), add='+')
# Создание базы данных
class DB:
def __init__(self):
self.conn = sqlite3.connect('bureau.db')
self.c = self.conn.cursor()
self.c.execute(
'''CREATE TABLE IF NOT EXISTS bureau (id integer primary key, project text,
status text, price real)''')
self.conn.commit()
def insert_data(self, project, status, price):
self.c.execute('''INSERT INTO bureau (project, status, price) VALUES (?, ?, ?) ''',
(project, status, price))
self.conn.commit()
# Основной код для запуска
if __name__ == "__main__":
root = tk.Tk()
db = DB()
app = Main(root)
app.pack()
root.geometry("665x500+300+200")
root.title("Проектное Бюро")
root.resizable(False, False)
root.mainloop()
Скриншот архива с проектом


Пояснения по запуску программы
Скачать PyCharm с оффициального сайта и установить. Открыть проект, запустить код из файла main.py с помощью кнопки Run.
Телеграм
-