當(dāng)前位置:博客首頁(yè)>>Python >> 閱讀正文

python的tkinter布局學(xué)習(xí)-簡(jiǎn)單的聊天窗口實(shí)現(xiàn)

作者: 鄭曉 分類: Python 發(fā)布于: 2013-12-14 12:49 瀏覽:21,214 評(píng)論(4)


學(xué)習(xí)python tkinter的時(shí)間順便寫了個(gè)簡(jiǎn)單的聊天窗口,可以實(shí)現(xiàn)下方輸入聊天內(nèi)容,點(diǎn)擊發(fā)送,可以增加到上方聊天記錄列表中?,F(xiàn)在只是“單機(jī)”版。
右側(cè)預(yù)留了空位可以放點(diǎn)兒其它東西。下一部是做成socket雙方互聊。
以下是代碼部分:

from tkinter import *
import datetime
import time
root = Tk()
root.title('與xxx聊天中')
#發(fā)送按鈕事件
def sendmessage():
#在聊天內(nèi)容上方加一行 顯示發(fā)送人及發(fā)送時(shí)間
msgcontent = '我:' + 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)建幾個(gè)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)建需要的幾個(gè)元素
text_msglist = Text(frame_left_top)
text_msg = Text(frame_left_center);
button_sendmsg = Button(frame_left_bottom, text='發(fā)送', command=sendmessage)
#創(chuàng)建一個(gè)綠色的tag
text_msglist.tag_config('green', foreground='#008B00')
#使用grid設(shè)置各個(gè)容器位置
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)
#把元素填充進(jìn)frame
text_msglist.grid()
text_msg.grid()
button_sendmsg.grid(sticky=E)
#主事件循環(huán)
root.mainloop()

以下是運(yùn)行截圖:
python_tkinter_聊天窗口

? ? ? ?

本文采用知識(shí)共享署名-非商業(yè)性使用 3.0 中國(guó)大陸許可協(xié)議進(jìn)行許可,轉(zhuǎn)載時(shí)請(qǐng)注明出處及相應(yīng)鏈接。

本文永久鏈接: http://www.yjfs.org.cn/python-tkinter-layout-of-learning-a-simple-chat-window-to-achieve.html

python的tkinter布局學(xué)習(xí)-簡(jiǎn)單的聊天窗口實(shí)現(xiàn):目前有4 條留言

用戶評(píng)論頭像 我真的想知道發(fā)表于 2018年09月07日 09:30[回復(fù)]

下一步的socket怎么結(jié)合這個(gè)界面,跪求答案

    用戶評(píng)論頭像 鄭曉發(fā)表于 2018年09月07日 15:03[回復(fù)]

    比如可以在sendmessage時(shí),向socket發(fā)送消息, socket接收到消息時(shí)也可以像sendmessage中這種操作,把消息insert到text組件中。

用戶評(píng)論頭像 夜溫州發(fā)表于 2013年12月17日 12:58[回復(fù)]

這個(gè)怎么用 ?? ?? ?? ??

用戶評(píng)論頭像 銀基網(wǎng)發(fā)表于 2013年12月17日 10:47[回復(fù)]

初來(lái)乍到,支持下

發(fā)表評(píng)論

change vcode