本文實例展示了一個python的tkinter布局的簡單聊天窗口。分享給大家供大家參考之用。具體方法如下:
該實例展示的是一個簡單的聊天窗口,可以實現(xiàn)下方輸入聊天內容,點擊發(fā)送,可以增加到上方聊天記錄列表中。現(xiàn)在只是“單機”版。
右側預留了空位可以放點兒其它東西。感興趣的讀者可以進一步做成socket雙方互聊。
以下是功能代碼部分:
from Tkinter import *import datetimeimport timeroot = Tk()root.title(unicode('與xxx聊天中','eucgb2312_cn'))#發(fā)送按鈕事件def sendmessage(): #在聊天內容上方加一行 顯示發(fā)送人及發(fā)送時間 msgcontent = unicode('我:','eucgb2312_cn') + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) + '/n ' text_msglist.insert(END, msgcontent, 'green') text_msglist.insert(END, text_msg.get('0.0', END)) text_msg.delete('0.0', END)#創(chuàng)建幾個frame作為容器frame_left_top = Frame(width=380, height=270, bg='white')frame_left_center = Frame(width=380, height=100, bg='white')frame_left_bottom = Frame(width=380, height=20)frame_right = Frame(width=170, height=400, bg='white')##創(chuàng)建需要的幾個元素text_msglist = Text(frame_left_top)text_msg = Text(frame_left_center);button_sendmsg = Button(frame_left_bottom, text=unicode('發(fā)送','eucgb2312_cn'), command=sendmessage)#創(chuàng)建一個綠色的tagtext_msglist.tag_config('green', foreground='#008B00')#使用grid設置各個容器位置frame_left_top.grid(row=0, column=0, padx=2, pady=5)frame_left_center.grid(row=1, column=0, padx=2, pady=5)frame_left_bottom.grid(row=2, column=0)frame_right.grid(row=0, column=1, rowspan=3, padx=4, pady=5)frame_left_top.grid_propagate(0)frame_left_center.grid_propagate(0)frame_left_bottom.grid_propagate(0)#把元素填充進frametext_msglist.grid()text_msg.grid()button_sendmsg.grid(sticky=E)#主事件循環(huán)root.mainloop()以下是運行截圖:

希望本文所述對大家的Python程序設計有所幫助
新聞熱點
疑難解答
圖片精選