首先項目需要的包
import urllib.request
import urllib.parse
from tkinter import *
import time
PS:另外很多人在學習Python的過程中,往往因為遇問題解決不了或者沒好的教程從而導致自己放棄,為此我整理啦從基礎的python腳本到web開發、爬蟲、django、數據挖掘等【PDF等】需要的可以進Python全棧開發交流.裙 :一久武其而而流一思(數字的諧音)轉換下可以找到了,里面有最新Python教程項目可拿,不懂的問題有老司機解決哦,一起相互監督共同進步
函數部分
說明:調用服務器接口,實現非特定智能回復
def get_robot_replay(question):
'''
函數功能:對於特定的問題進行特定的回答,對於其他非特定的問題進行智能回復
參數描述:
question:聊天內容或者問題
返回值:str,回復內容
'''
if "你叫什么名字"in question:
answer ="我是游游"
elif "你多少歲"in question:
answer="18"
elif "你是GG還是MM"in question:
answer="MM"
else:
try:
# 調用NLP接口實現智能回復
params=urllib.parse.urlencode({'msg':question}).encode() #將str轉換成字節類型,參數接口需要進行URL編碼
req = urllib.request.Request("http://api.itmojun.com/chat_robot",params,method="POST")#創建請求對象
answer=urllib.request.urlopen(req).read().decode()#調用接口(向目標服務器發送HTTP請求)
except Exception as e:
answer="AI機器人出現故障!(原因:%s)" % e
return answer
回復格式方面以及界面設計
def msgsend():
msg = '我' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\n'
txt_msglist.insert(END, msg, 'green') # 添加時間
txt_msglist.insert(END, txt_msgsend.get('0.0', END)) # 獲取發送消息,添加文本到消息列表
msg1 = '游游大寶貝' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\n'
txt_msglist.insert(END, msg1, 'green') # 添加時間
txt_msglist.insert(END,get_robot_replay(txt_msgsend.get('0.0', END)))
txt_msgsend.delete('0.0', END) # 清空發送消息
def cancel():
txt_msgsend.delete('0.0', END) # 取消發送消息,即清空發送消息
'''綁定up鍵'''
def msgsendEvent(event):
if event.keysym == 'Up':
msgsend()
聊天界面設計
tk = Tk()
tk.title('和游游大寶貝的秘聊')
'''創建分區'''
f_msglist = Frame(height=300, width=300) # 創建<消息列表分區 >
f_msgsend = Frame(height=300, width=300) # 創建<發送消息分區 >
f_floor = Frame(height=100, width=300) # 創建<按鈕分區>
f_right = Frame(height=700, width=100) # 創建<圖片分區>
'''創建控件'''
txt_msglist = Text(f_msglist) # 消息列表分區中創建文本控件
txt_msglist.tag_config('green', foreground='blue') # 消息列表分區中創建標簽
txt_msgsend = Text(f_msgsend) # 發送消息分區中創建文本控件
txt_msgsend.bind('<KeyPress-Up>', msgsendEvent) # 發送消息分區中,綁定‘UP’鍵與消息發送。
'''txt_right = Text(f_right) #圖片顯示分區創建文本控件'''
button_send = Button(f_floor, text='Sendz', command=msgsend) # 按鈕分區中創建按鈕並綁定發送消息函數
button_cancel = Button(f_floor, text='Cancel', command=cancel) # 分區中創建取消按鈕並綁定取消函數
'''分區布局'''
f_msglist.grid(row=0, column=0) # 消息列表分區
f_msgsend.grid(row=1, column=0) # 發送消息分區
f_floor.grid(row=2, column=0) # 按鈕分區
f_right.grid(row=0, column=1, rowspan=3) # 圖片顯示分區
txt_msglist.grid() # 消息列表文本控件加載
txt_msgsend.grid() # 消息發送文本控件加載
button_send.grid(row=0, column=0, sticky=W) # 發送按鈕控件加載
button_cancel.grid(row=0, column=1, sticky=W) # 取消按鈕控件加載
tk.mainloop()
運行截圖
不錯吧。另外很多人在學習Python的過程中,往往因為遇問題解決不了或者沒好的教程從而導致自己放棄,為此我整理啦從基礎的python腳本到web開發、爬蟲、django、數據挖掘等【PDF等】需要的可以進Python全棧開發交流.裙 :一久武其而而流一思(數字的諧音)轉換下可以找到了,里面有最新Python教程項目可拿,不懂的問題有老司機解決哦,一起相互監督共同進步
本文的文字及圖片來源於網絡加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。