python编程-16:tkinter绘制聊天窗口_彭世瑜_新浪博客

209 阅读1分钟

python编程-16:tkinter绘制聊天窗口

python编程-16:tkinter绘制聊天窗口
\

\

源码:

  1. from tkinter import *
  2. import time
  3.  
  4. def main():
  5.  
  6.   def sendMsg():#发送消息
  7.     strMsg = '我:' + time.strftime("%Y-%m-%d %H:%M:%S",
  8.                                   time.localtime()) + '\n '
  9.     txtMsgList.insert(END, strMsg, 'greencolor')
  10.     txtMsgList.insert(END, txtMsg.get('0.0', END))
  11.     txtMsg.delete('0.0', END)
  12.      
  13.   def cancelMsg():#取消消息
  14.     txtMsg.delete('0.0', END)
  15.  
  16.   def sendMsgEvent(event): #发送消息事件
  17.     if event.keysym == "Up":
  18.       sendMsg()
  19.  
  20.   #创建窗口 
  21.   t = Tk()
  22.   t.title('与python聊天中')
  23.        
  24.   #创建frame容器
  25.   frmLT = Frame(width=500, height=320, bg='white')
  26.   frmLC = Frame(width=500, height=150, bg='white')
  27.   frmLB = Frame(width=500, height=30)
  28.   frmRT = Frame(width=200, height=500)
  29.    
  30.   #创建控件
  31.   txtMsgList = Text(frmLT)
  32.   txtMsgList.tag_config('greencolor', foreground='#008C00')#创建tag
  33.   txtMsg = Text(frmLC);
  34.   txtMsg.bind("", sendMsgEvent)
  35.   btnSend = Button(frmLB, text='发 送', width = 8, command=sendMsg)
  36.   btnCancel = Button(frmLB, text='取消', width = 8, command=cancelMsg)
  37.   imgInfo = PhotoImage(file = "python.gif")
  38.   lblImage = Label(frmRT, image = imgInfo)
  39.   lblImage.image = imgInfo
  40.  
  41.   #窗口布局
  42.   frmLT.grid(row=0, column=0, columnspan=2, padx=1, pady=3)
  43.   frmLC.grid(row=1, column=0, columnspan=2, padx=1, pady=3)
  44.   frmLB.grid(row=2, column=0, columnspan=2)
  45.   frmRT.grid(row=0, column=2, rowspan=3, padx=2, pady=3)
  46.   #固定大小
  47.   frmLT.grid_propagate(0)
  48.   frmLC.grid_propagate(0)
  49.   frmLB.grid_propagate(0)
  50.   frmRT.grid_propagate(0)
  51.    
  52.   btnSend.grid(row=2, column=0)
  53.   btnCancel.grid(row=2, column=1)
  54.   lblImage.grid()
  55.   txtMsgList.grid()
  56.   txtMsg.grid()
  57.  
  58.   #主事件循环
  59.   t.mainloop()
  60.  
  61. if __name__ == '__main__':
  62.     main()

\

\

原文地址: www.icourse163.org/learn/BIT-2…