Code
import tkinter as tk
import mysql.connector
import subprocess
from tkinter import Label, Toplevel
from tkinter import messagebox as mb
def getUUID():
x = subprocess.check_output('wmic csproduct get UUID')
return x.decode()[41:77]
mydb = mysql.connector.connect(
host = "",
user = "",
password = "",
database = ""
)
mycursor = mydb.cursor()
user = ""
def createRoom():
global mycursor
id = createRoomInput.get(1.0 ,"end-1c")
if len(id) == 10:
mycursor.execute(f"SELECT * FROM `room_info` WHERE id='{id}'")
myresult = mycursor.fetchall()
if len(myresult) == 0:
mycursor.execute(f"CREATE TABLE `{id}` (`order` INT NOT NULL AUTO_INCREMENT,`uuid` VARCHAR(45) NOT NULL,PRIMARY KEY (`order`))ENGINE = MyISAM;")
mycursor.execute(f"INSERT INTO `room_info`(`id`,`admin`) VALUES ('{id}','{getUUID()}')")
mycursor.execute(f"INSERT INTO `{id}` (`uuid`) VALUES ('{getUUID()}');")
mb.showinfo("Create room successfully!", "Information")
else: mb.showerror("Room already exsited!", "Error")
else: mb.showerror("Id cannot exceed 10 characters!", "Error")
def joinRoom():
global mycursor
global mydb
global user
def send_message():
room = joinRoomInput.get(1.0, "end-1c")
message = messagebox_send.get(1.0, "end-1c")
if message != "":
if user != "Admin":
mycursor.execute(f"INSERT INTO `check_messages` (`name`,`message`,`room`,`time`) VALUES ('{user}','{message}','{room}',NOW());")
mydb.commit()
else:
mycursor.execute(f"INSERT INTO `messages` (`name`,`message`,`room`,`time`) VALUES ('{user}','{message}','{room}',NOW());")
mydb.commit()
messagebox.config(state="normal")
messagebox.insert(tk.END,f"\n{user}: {message}")
messagebox.config(state="disabled")
else:
mb.showerror("", "Error")
def check_messages():
def refuse():
mycursor.execute(f"SELECT * FROM `check_messages` WHERE `room`='{room}' ORDER BY `time`;")
message_wait = mycursor.fetchall()
mycursor.execute(f"DELETE FROM `check_messages` WHERE `room`='{room}' AND `name`='{message_wait[0][0]}' AND `message`='{message_wait[0][1]}';")
mydb.commit()
frame_check.destroy()
def agree():
mycursor.execute(f"SELECT * FROM `check_messages` WHERE `room`='{room}' ORDER BY `time`;")
message_wait = mycursor.fetchall()
mycursor.execute(f"DELETE FROM `check_messages` WHERE `room`='{room}' AND `name`='{message_wait[0][0]}' AND `message`='{message_wait[0][1]}';")
mydb.commit()
messagebox["state"] = "normal"
messagebox.insert(tk.END, f"\n{message_wait[0][0]}: {message_wait[0][1]}")
messagebox["state"] = "disabled"
mycursor.execute(f"INSERT INTO `messages` (`name`,`message`,`room`,`time`) VALUES ('{message_wait[0][0]}','{message_wait[0][1]}','{room}',NOW());")
mydb.commit()
frame_check.destroy()
if user == "Admin":
mycursor.execute(f"SELECT * FROM `check_messages` WHERE `room`='{room}' ORDER BY `time`;")
message_wait = mycursor.fetchall()
frame_check = Toplevel()
frame_check.geometry("300x200")
frame_check.resizable(width=False, height=False)
header = Label(frame_check, height=1,width=300,text=f"{message_wait[0][0]} WANT TO SEND THIS MESSAGE")
header.pack()
mbc = tk.Text(frame_check, height=2,width=300)
mbc.pack()
mbc.insert(tk.END, f"{message_wait[0][1]}")
mbc['state'] = 'disabled'
no = tk.Button(frame_check, text="NO", command=refuse)
no.pack()
yes = tk.Button(frame_check, text="YES", command=agree)
yes.pack()
room = joinRoomInput.get(1.0, "end-1c")
mycursor.execute(f"SELECT * FROM `main`.`room_info` WHERE id = '{room}'")
if len(mycursor.fetchall()) == 1:
joinRoomInput.config(state="disabled")
joinRoomButton.config(state="disabled")
mycursor.execute(f"SELECT * FROM `{room}` WHERE uuid='{getUUID()}'")
result = mycursor.fetchall()
if len(result) == 1:
if int(result[0][0]) != 1: user = f"P[{result[0][0]}]"
else: user = "Admin"
else:
mycursor.execute(f"INSERT INTO `{room}`(`uuid`) VALUES ('{getUUID()}');")
mycursor.execute(f"SELECT * FROM `{room}` WHERE uuid='{getUUID()}'")
result = mycursor.fetchall()
user = f"P[{result[0][0]}]"
frame = Toplevel()
frame.resizable(width=False,height=False)
frame.geometry("700x600")
room_name = Label(frame,height=1,width=700,text=str(room))
room_name.pack()
messagebox = tk.Text(frame, height=20, width=700)
messagebox.pack()
mycursor.execute(f"SELECT * FROM `messages` WHERE `room` = '{room}' ORDER BY `time`;")
messages_load = mycursor.fetchall()
for x in messages_load:
messagebox.insert(tk.END, f"\n{x[0]}: {x[1]}")
messagebox.config(state="disabled")
messagebox_send = tk.Text(frame, height=12, width=700)
messagebox_send.pack()
send = tk.Button(frame, text="Send", command=send_message)
send.pack()
check = tk.Button(frame, text="Waiting message", command=check_messages)
check.pack()
else:
mb .showerror("Can't find room!", "Error")
window = tk.Tk()
window.resizable(width=False, height=False)
window.geometry("300x200")
createRoomInput = tk.Text(window, height = 2,width = 300)
createRoomInput.pack()
createRoomButton = tk.Button(window, text="Create Room", command=createRoom)
createRoomButton.pack()
joinRoomInput = tk.Text(window, height = 2,width = 300)
joinRoomInput.pack()
joinRoomButton = tk.Button(window, text="Join Room", command=joinRoom)
joinRoomButton.pack()
window.mainloop()
Note
+ 128 dòng code đấy :))
+ Test thì nhớ install subprocess (pip install subprocess.run) và mysql (pip install mysql-connector-python) nhá
+ Nó có hơi khác so với đề bài, cái phần duyệt tin nhắn chờ thì chủ phòng phải ấn vào cái nút 'Waiting message' để check và duyệt. Còn cái phần khi chủ phòng thoát thì đóng phòng không làm được (khó, chưa học, lười và sắp thi) :))
+ Cái này dùng UUID của mỗi máy để phân biệt
+ Có mấy dòng lúc đang trả lời mới thêm vào có thể bị lỗi 'IndentationError' tự sửa nha
+ Tải MySQL Server Community về mà dùng
+ Có thể thay thế mấy cái tên bảng và tên cột không thì dùng mấy cái bảng này:
CREATE TABLE `check_messages` (
`name` varchar(225) COLLATE utf8mb4_vietnamese_ci NOT NULL,
`message` varchar(225) COLLATE utf8mb4_vietnamese_ci NOT NULL,
`room` varchar(10) COLLATE utf8mb4_vietnamese_ci NOT NULL,
`time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_vietnamese_ci;
CREATE TABLE `messages` (
`name` varchar(100) COLLATE utf8mb4_vietnamese_ci NOT NULL,
`message` varchar(4500) COLLATE utf8mb4_vietnamese_ci NOT NULL,
`room` varchar(10) COLLATE utf8mb4_vietnamese_ci NOT NULL,
`time` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_vietnamese_ci;
CREATE TABLE `room_info` (
`id` varchar(10) COLLATE utf8mb4_vietnamese_ci NOT NULL,
`admin` varchar(45) COLLATE utf8mb4_vietnamese_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_vietnamese_ci;
+ Test thì tắt cái từ chối DELETE của MySQL mới được không lỗi đấy
+ Có mấy chỗ chưa debug được chạy vẫn lỗi (Nhưng đa số không ảnh hưởng mấy)
+ Tôi test nhiều rồi không chạy lỗi đâu, có lỗi thì hỏi để tôi còn xem lại
+ Mà sao ông này hỏi toàn câu khó rồi gắn tag lớp 7 nhỉ :))
Tin học, tiếng Anh: informatics, tiếng Pháp: informatique, là một ngành khoa học chuyên nghiên cứu quá trình tự động hóa việc tổ chức, lưu trữ, xử lý và truyền dẫn thông tin của một hệ thống máy tính cụ thể hoặc trừu tượng (ảo). Với cách hiểu hiện nay, tin học bao hàm tất cả các nghiên cứu và kỹ thuật có liên quan đến việc mô phỏng, biến đổi và tái tạo thông tin.
Nguồn : Wikipedia - Bách khoa toàn thưLớp 7 - Năm thứ hai ở cấp trung học cơ sở, một cuồng quay mới lại đến vẫn bước tiếp trên đường đời học sinh. Học tập vẫn là nhiệm vụ chính!
Nguồn : ADMIN :))Copyright © 2021 HOCTAP247