Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
КР_ТПП.docx
Скачиваний:
1
Добавлен:
12.04.2025
Размер:
6.76 Mб
Скачать

Список используемой литературы

1. Обучение Python GUI [Электронный ресурс] URL: https://proglib.io/p/python-i-mysql-prakticheskoe-vvedenie-2021-01-06 (Дата обращения 23.11.2023)

2. Python и MySQL: практическое введение [Электронный ресурс] URL: https://proglib.io/p/python-i-mysql-prakticheskoe-vvedenie-2021-01-06 (Дата обращения 03.12.2023)

3. Виджет Python Tkinter messagebox- диалоговые окна сообщений [Электронный ресурс] URL: https://pythonpip.ru/osnovy/vidzhet-python-tkinter-messagebox-dialogovye-okna-soobscheniy (Дата обращения 05.12.2023)

Приложение а

import tkinter as tk

import sys

from tkinter import messagebox

w1 = tk.Tk()

w1.geometry("1000x720")

# w1.title("Регистрация')

uservalue = tk.StringVar()

user2value = tk.StringVar()

passvalue = tk.StringVar()

pass2value = tk.StringVar()

confpassvalue = tk.StringVar()

emailvalue = tk.StringVar()

counter = 0

fiovalue= tk.StringVar()

datavalue= tk.StringVar()

countryvalue= tk.StringVar()

passportvalue=tk.StringVar()

passentry= tk.StringVar()

selected_seat_number=tk.StringVar()

passentry1=tk.StringVar()

def login1():

if uservalue.get() == "" or passvalue.get() == "":

messagebox.showerror("Error", "Все поля пустые", parent=w1)

sys.exit()

import mysql.connector as con

connection = con.connect(host="localhost", user="root", password="Coolgirl.2003", database="irsts")

cursor = connection.cursor()

cursor.execute("select count(*) from data")

afetch = cursor.fetchone()

bfetch = afetch[0]

username = uservalue.get()

password = passvalue.get()

cursor.execute('select username,password from data where username=username and password=password')

row = cursor.fetchall()

global counter

for i in range(0, bfetch):

if (row[i][0] == username and row[i][1] == password):

counter = 1

if (counter == 1):

messagebox.showinfo("Found", "Вход успешный")

messagebox.showinfo("Hello", "Чтобы продолжить, закройте окно")

print("found")

else:

messagebox.showinfo("Not found", "Неправильный логин или пароль")

connection.close()

window()

def window():

f = tk.PhotoImage(file="img_5.png")

background_label = tk.Label(w1, image=f)

background_label.place(x=0, y=0, relwidth=1, relheight=1)

frame_input = tk.Frame(w1, bg='pink')

frame_input.place(x=320, y=130, height=400, width=400)

btn3 = tk.Button(frame_input, text="Купить билет на самолет", font=("Century Gothic", 16, "bold"), bg='#E6E6FA', fg="black",

command=bilet)

btn3.place(relx=0.5, rely=0.22, anchor=tk.CENTER)

btn4 = tk.Button(frame_input, text="Забронировать билет", font=("Century Gothic", 16, "bold"),

bg='#E6E6FA', fg="black", command=bron)

btn4.place(relx=0.5, rely=0.4, anchor=tk.CENTER)

btn5 = tk.Button(frame_input, text="Отменить бронирование", font=("Century Gothic", 16, "bold"),

bg='#E6E6FA', fg="black", command=drop_bron)

btn5.place(relx=0.5, rely=0.58, anchor=tk.CENTER)

w1.mainloop()

def bilet():

f = tk.PhotoImage(file="img_8.png")

background_label = tk.Label(w1, image=f)

background_label.place(x=0, y=0, relwidth=1, relheight=1)

global fiovalue

global datavalue

global countryvalue

global passportvalue

frame_input = tk.Frame(w1, bg='gray')

frame_input.place(x=320, y=100, height=600, width=400)

tk.Label(text="Введите данные", font=("Century Gothic", 28, "bold"), fg="black", bg='pink',

relief=tk.RIDGE).place(x=390, y=136)

tk.Label(text="ФИО", font=("Century Gothic", 25), fg="black", relief=tk.RIDGE).place(x=340, y=200)

fioentry = tk.Entry(font=("Century Gothic", 22, "bold"), fg="black", bg='pink', textvariable=fiovalue)

fioentry.place(x=340, y=250)

tk.Label(text="Дата", font=("Century Gothic", 20), fg="black", borderwidth=3, relief=tk.RIDGE).place(x=340, y=300)

dataentry = tk.Entry(font=("Century Gothic", 20, "bold"), fg="black", bg='pink', textvariable=datavalue)

dataentry.place(x=340, y=350)

tk.Label(text="Страна", font=("Century Gothic", 20), fg="black", borderwidth=3, relief=tk.RIDGE).place(x=340, y=400)

countryentry = tk.Entry(font=("Century Gothic", 22, "bold"), fg="black", bg='pink', textvariable=countryvalue)

countryentry.place(x=340, y=450)

tk.Label(text="Номер паспорта", font=("Century Gothic", 20), fg="black", borderwidth=3, relief=tk.RIDGE).place(x=340, y=500)

passportentry = tk.Entry(font=("Century Gothic", 22, "bold"), fg="black", bg='pink', textvariable=passportvalue)

passportentry.place(x=340, y=550)

bt = tk.Button(frame_input, text="Купить билет", font=("Century Gothic", 16, "bold"), bg='pink',fg="black", command=pokupka)

bt.place(relx=0.5, rely=0.90, anchor=tk.CENTER)

btnsss = tk.Button(frame_input, text="⬅", font=("Century Gothic", 17, "bold"),

bg="pink", fg="black", command=window)

btnsss.place(relx=0.1, rely=0.1, anchor=tk.CENTER)

w1.mainloop()

def pokupka():

printfio = fiovalue.get()

printdata = datavalue.get()

printcountry = countryvalue.get()

printpassport = passportvalue.get()

if (printfio == "" or printdata == "" or printcountry == "" or printpassport == ""):

messagebox.showerror("Error", "Пустые поля", parent=w1)

else:

import mysql.connector as con

connection = con.connect(host="localhost", user="root", password="Coolgirl.2003", database="irsts")

cursor = connection.cursor()

cursor.execute("INSERT INTO bilet (fio , data , country, passport) VALUES (%s, %s , %s, %s)",

(printfio, printdata, printcountry, printpassport))

connection.commit()

connection.close()

messagebox.showinfo("Registered", "Вы успешно купили билет")

messagebox.showinfo("DONE!!!", "Можете забронировать место")

def bron ():

f = tk.PhotoImage(file="img_15.png")

background_label = tk.Label(w1, image=f)

background_label.place(x=0, y=0, relwidth=1, relheight=1)

global passentry

frame_input = tk.Frame(w1, bg='gray')

frame_input.place(x=320, y=100, height=270, width=400)

tk.Label(text="Введите номер паспорта", font=("Century Gothic", 18, "bold"), fg="black", bg='darkgray',

relief=tk.RIDGE).place(x=390, y=110)

tk.Label(text="Номер", font=("Century Gothic", 25), fg="black", relief=tk.RIDGE).place(x=340, y=200)

passpentry = tk.Entry(font=("Century Gothic", 22, "bold"), fg="black", bg='white', textvariable=passentry)

passpentry.place(x=340, y=250)

bt = tk.Button(frame_input, text="Забронировать", font=("Century Gothic", 16, "bold"), bg='white', fg="black",

command=brons)

bt.place(relx=0.5, rely=0.90, anchor=tk.CENTER)

btnsss = tk.Button(frame_input, text="⬅", font=("Century Gothic", 15, "bold"),

bg="white", fg="black", command=window)

btnsss.place(relx=0.1, rely=0.1, anchor=tk.CENTER)

w1.mainloop()

def brons():

f = tk.PhotoImage(file="img_15.png")

background_label = tk.Label(w1, image=f)

background_label.place(x=0, y=0, relwidth=1, relheight=1)

booking_enabled = False

seat_buttons = []

global selected_seat_number

frame_input = tk.Frame(w1, bg='gray')

frame_input.place(x=320, y=100, height=550, width=350)

tk.Label(text="Выберите место", font=("Century Gothic", 18, "bold"), fg="black", bg='white',

relief=tk.RIDGE).place(x=390, y=136)

def select_seat(seat_number):

print(f"Выбрано сиденье номер {seat_number}")

seat_buttons[seat_number - 1].config(relief=tk.SUNKEN, bg="gray")

selected_seat_number.set(str(seat_number))

def create_seat_buttons():

num_rows = 15 # Количество строк с сиденьями

num_seats_per_row = 4 # Количество сидений в каждой строке

row_spacing = 20 # Расстояние между рядами

global selected_seat_number

frame_input.grid_rowconfigure(0, weight=1) # Расположение по вертикали

frame_input.grid_columnconfigure(0, weight=1) # Расположение по горизонтали

seat_frame = tk.Frame(frame_input, bg='gray')

seat_frame.grid(row=0, column=0, sticky='nsew') # Выравнивание по центру

button_width = 3 # Ширина кнопки

button_height = 1 # Высота кнопки

# Создание сидений с учетом интервала между рядами

for i in range(num_rows):

for j in range(num_seats_per_row):

seat_number = i * num_seats_per_row + j + 1

seat_button = tk.Button(seat_frame, text=f"{seat_number}", width=button_width, height=button_height,

command=lambda num=seat_number: select_seat(num), activebackground="gray30")

seat_button.grid(row=i, column=j, padx=3, pady=0) # Добавление расстояния между рядами

seat_buttons.append(seat_button) # Добавляем кнопку в список

# Расположение фрейма самолета по центру

seat_frame.grid_rowconfigure(0, weight=1)

seat_frame.grid_columnconfigure(0, weight=1)

seat_frame.place(relx=0.5, rely=0.5, anchor=tk.CENTER) # Размещение фрейма по центру формы

create_seat_buttons()

def book_seats():

passp = passentry.get()

number = selected_seat_number.get()

import mysql.connector as con

connection = con.connect(host="localhost", user="root", password="Coolgirl.2003", database="irsts")

cursor = connection.cursor()

cursor.execute("SELECT * FROM bilet WHERE passport = %s", (passp,))

passenger = cursor.fetchone()

print(selected_seat_number.get())

print(passp)

if passenger:

try:

cursor.execute("SELECT * FROM bron WHERE passport = %s", (passp,))

existing_booking = cursor.fetchone()

if existing_booking:

messagebox.showinfo("Already Booked", "Бронирование уже совершено для данного пассажира.")

else:

cursor.execute("INSERT INTO bron (passport, seat) VALUES (%s, %s)", (passp, number))

connection.commit()

print("Данные успешно добавлены в таблицу 'bron'.")

messagebox.showinfo("Registered", "Вы успешно забронировали место")

except Exception as e:

connection.rollback()

print(f"Произошла ошибка: {str(e)}")

messagebox.showerror("Error", "Произошла ошибка при обращении к базе данных.")

finally:

connection.close()

else:

messagebox.showerror("Error", "Пассажир с таким номером паспорта не найден.")

bt = tk.Button(frame_input, text="Забронировать", font=("Century Gothic", 16, "bold"), bg='white', fg="black",

command=book_seats)

bt.place(relx=0.5, rely=0.96, anchor=tk.CENTER)

btnsss = tk.Button(frame_input, text="⬅", font=("Century Gothic", 15, "bold"),

bg="white", fg="black", command=window)

btnsss.place(relx=0.1, rely=0.1, anchor=tk.CENTER)

w1.mainloop()

def drop_bron ():

f = tk.PhotoImage(file="img_21.png")

background_label = tk.Label(w1, image=f)

background_label.place(x=0, y=0, relwidth=1, relheight=1)

global passentry1

frame_input = tk.Frame(w1, bg='black')

frame_input.place(x=320, y=100, height=370, width=400)

tk.Label(text="Введите номер паспорта", font=("Century Gothic", 18, "bold"), fg="black", bg='pink',

relief=tk.RIDGE).place(x=390, y=120)

tk.Label(text="Номер", font=("Century Gothic", 18), bg='pink',fg="black", relief=tk.RIDGE).place(x=340, y=200)

passpentry1 = tk.Entry(font=("Century Gothic", 18, "bold"), fg="black", bg='pink', textvariable=passentry1)

passpentry1.place(x=340, y=250)

bt = tk.Button(frame_input, text="Отменить бронирование", font=("Century Gothic", 16, "bold"), bg='pink', fg="black",

command=drop_brons)

bt.place(relx=0.5, rely=0.70, anchor=tk.CENTER)

bt = tk.Button(frame_input, text="Забронировать еще раз", font=("Century Gothic", 16, "bold"), bg='pink',

fg="black",

command=brons)

bt.place(relx=0.5, rely=0.90, anchor=tk.CENTER)

btnsss = tk.Button(frame_input, text="⬅", font=("Century Gothic", 15, "bold"),

bg="pink", fg="black", command=window)

btnsss.place(relx=0.1, rely=0.1, anchor=tk.CENTER)

w1.mainloop()

def drop_brons():

passp = passentry1.get()

import mysql.connector as con

connection = con.connect(host="localhost", user="root", password="Coolgirl.2003", database="irsts")

cursor = connection.cursor()

cursor.execute("SELECT * FROM bilet WHERE passport = %s", (passp,))

passenger = cursor.fetchone()

if passenger:

try:

cursor.execute("DELETE FROM bron WHERE passport = %s", (passp,))

connection.commit()

print("Запись успешно удалена из таблицы 'bron'.")

messagebox.showinfo("Deleted", "Бронирование удалено!")

except Exception as e:

connection.rollback()

print(f"Произошла ошибка: {str(e)}")

messagebox.showerror("Error", "Произошла ошибка при удалении записи из базы данных.")

finally:

connection.close()

else:

messagebox.showerror("Error", "Пассажир с таким номером паспорта не найден.")

def signup1():

f = tk.PhotoImage(file="img_3.png") # This is only for .png files for .jpg use PIL

background_label = tk.Label(w1, image=f)

background_label.place(x=0, y=0, relwidth=1, relheight=1)

global user2value

global pass2value

global confpassvalue

global emailvalue

frame_input2 = tk.Frame(w1, bg='pink')

frame_input2.place(x=320, y=130, height=500, width=400)

tk.Label(text="Регистрация", font=("Century Gothic", 28, "bold"), fg="black", borderwidth=4, bg='pink',

relief=tk.RIDGE).place(x=400, y=150)

tk.Label(text="Логин", font=("Century Gothic", 25), fg="black", borderwidth=3, relief=tk.RIDGE).place(x=340, y=230)

uentry2 = tk.Entry(font=("Century Gothic", 22, "bold"), fg="black", bg="darkgray", textvariable=user2value)

uentry2.place(x=340, y=280)

tk.Label(text="Пароль", font=("Century Gothic", 24), fg="black", borderwidth=3, relief=tk.RIDGE).place(x=340, y=340)

passentry2 = tk.Entry(font=("Century Gothic", 22, "bold"), fg="black", bg="darkgray", textvariable=pass2value)

passentry2.place(x=340, y=390)

tk.Label(text="Почта", font=("Century Gothic", 25), fg="black", borderwidth=3, relief=tk.RIDGE).place(x=340,y=450)

emailentry= tk.Entry( font=("Century Gothic", 22, "bold"), fg="black", bg="darkgray", textvariable=emailvalue)

emailentry.place(x=340, y=500)

btns = tk.Button(frame_input2, text="Зарегестрироваться", font=("Century Gothic", 16, "bold"), bg="pink", fg="black",

command=signup2)

btns.place(relx=0.5, rely=0.90, anchor=tk.CENTER)

btnss = tk.Button(frame_input2, text="⬅", font=("Century Gothic", 14, "bold"),

bg="pink", fg="black", command=main)

btnss.place(relx=0.1, rely=0.15, anchor=tk.CENTER)

w1.mainloop()

def signup2():

printuser = user2value.get()

printpass = pass2value.get()

printemail = emailvalue.get()

print("Username:", printuser)

print("Email:", printemail)

print("Password:", printpass)

if (printuser == "" or printemail == "" or printpass == ""):

messagebox.showerror("Error", "Пустые поля", parent=w1)

else:

import mysql.connector as con

connection = con.connect(host="localhost", user="root", password="Coolgirl.2003", database="irsts")

cursor = connection.cursor()

cursor.execute("INSERT INTO data (username,password,email) VALUES (%s, %s , %s)",

(printuser, printpass, printemail))

connection.commit()

connection.close()

messagebox.showinfo("Registered", "Вы успешно зарегестрированы")

messagebox.showinfo("DONE!!!", "Войдите, чтобы продолжить")

# w1.mainloop()

def main():

f=tk.PhotoImage(file="img_3.png")

background_label=tk.Label(w1,image=f)

background_label.place(x=0,y=0,relwidth=1,relheight=1)

global uservalue

global passvalue

frame_input=tk.Frame(w1,bg='pink')

frame_input.place(x=320,y=130,height=500,width=400)

tk.Label(text="Вход", font=("Century Gothic",30,"bold"), fg="black",borderwidth=4,bg='pink', relief=tk.RIDGE).place(x=470,y=150)

tk.Label(text="Логин",font=("Century Gothic",25),fg="black",borderwidth=3, relief=tk.RIDGE).place(x=340,y=230)

tk.Label(text="Пароль",font=("Century Gothic",24),fg="black",borderwidth=3, relief=tk.RIDGE).place(x=340,y=340)

userentry=tk.Entry(w1,font=("Century Gothic",22,"bold"),fg="black",bg="darkgray",textvariable=uservalue)

passwordentry=tk.Entry(w1,font=("Century Gothic",22,"bold"),fg="black",bg="darkgray",textvariable=passvalue)

userentry.place(x=340,y=280)

passwordentry.place(x=340,y=390)

btn1=tk.Button(frame_input,text="Вход",font=("Century Gothic",16,"bold"),bg="pink",fg="black",command=login1)

btn1.place(relx=0.5, rely=0.72, anchor=tk.CENTER)

btn2=tk.Button(frame_input,text="Нет аккаунта? Регистрация",font=("Century Gothic",16,"bold"),

bg="pink",fg="black",command=signup1)

btn2.place(relx=0.5, rely=0.88, anchor=tk.CENTER)

w1.mainloop()

main()

42

Соседние файлы в предмете Технологии программирования