You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

121 lines
3.6 KiB

import pyttsx3
import tkinter as tk
import threading
import speech_recognition as sr
# Initialize speech synthesis object
talker = pyttsx3.init()
# Initialize speech recognition object
recognizer = sr.Recognizer()
# Login credentials
userName = "admin"
userPass = "123"
# Create chat window
def chat_window():
chat_window = tk.Tk()
chat_window.title("对话")
chat_window.geometry("800x400")
def chat():
question = input_entry.get()
answer = question.strip("吗??" + "!")
if question == "不聊了拜拜":
talker.say("好的,拜拜就拜拜!")
talker.runAndWait()
chat_window.destroy()
else:
chat_text.insert(tk.END, "你: " + question + "\n")
chat_text.insert(tk.END, "机器人的回答:" + answer + "\n")
talker_thread = threading.Thread(target=speak, args=(answer,))
talker_thread.start()
input_entry.delete(0, tk.END)
def speak(answer):
talker.say(answer)
talker.runAndWait()
def voice_recognition():
with sr.Microphone() as source:
print("请说话...")
audio = recognizer.listen(source)
try:
print("识别中...")
question = recognizer.recognize_google(audio, language="zh-CN")
print("你说: " + question)
answer = question.strip("吗??" + "!")
if question == "不聊了拜拜":
talker.say("好的,拜拜就拜拜!")
talker.runAndWait()
chat_window.destroy()
else:
chat_text.insert(tk.END, "你: " + question + "\n")
chat_text.insert(tk.END, "机器人的回答:" + answer + "\n")
talker_thread = threading.Thread(target=speak, args=(answer,))
talker_thread.start()
except sr.UnknownValueError:
print("抱歉, 未能识别,请重试")
chat_text = tk.Text(chat_window)
chat_text.pack()
input_entry = tk.Entry(chat_window)
input_entry.pack()
send_button = tk.Button(chat_window, text="发送", command=chat)
send_button.pack()
voice_button = tk.Button(chat_window, text="语音识别", command=voice_recognition)
voice_button.pack()
chat_window.mainloop()
# 创建登录窗口
def login_window():
login_window = tk.Tk()
login_window.title("登录")
# 获取屏幕宽度和高度
screen_width = login_window.winfo_screenwidth()
screen_height = login_window.winfo_screenheight()
# 设置窗口居中
window_width = 300
window_height = 200
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
login_window.geometry(f"{window_width}x{window_height}+{x}+{y}")
def login():
inputName = name_entry.get()
inputPass = pass_entry.get()
if inputName == userName and inputPass == userPass:
talker.say("恭喜你登录成功!")
talker.runAndWait()
login_window.destroy()
chat_window()
else:
talker.say("账号或密码错误,登录失败")
talker.runAndWait()
name_label = tk.Label(login_window, text="用户名:")
name_label.pack()
name_entry = tk.Entry(login_window)
name_entry.pack()
pass_label = tk.Label(login_window, text="密码:")
pass_label.pack()
pass_entry = tk.Entry(login_window, show="*")
pass_entry.pack()
login_button = tk.Button(login_window, text="登录", command=login)
login_button.pack()
login_window.mainloop()
# 自然语言处理功能
# 启动登录窗口
login_window()