python的tkinter布局之简单的聊天窗口实现方法

yipeiwu_com6年前Python基础

本文实例展示了一个python的tkinter布局的简单聊天窗口。分享给大家供大家参考之用。具体方法如下:

该实例展示的是一个简单的聊天窗口,可以实现下方输入聊天内容,点击发送,可以增加到上方聊天记录列表中。现在只是“单机”版。
右侧预留了空位可以放点儿其它东西。感兴趣的读者可以进一步做成socket双方互聊。

以下是功能代码部分:

from Tkinter import *
import datetime
import time
root = Tk()
root.title(unicode('与xxx聊天中','eucgb2312_cn'))
#发送按钮事件
def sendmessage():
  #在聊天内容上方加一行 显示发送人及发送时间
  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)

#创建几个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')
##创建需要的几个元素
text_msglist    = Text(frame_left_top)
text_msg      = Text(frame_left_center);
button_sendmsg   = Button(frame_left_bottom, text=unicode('发送','eucgb2312_cn'), command=sendmessage)
#创建一个绿色的tag
text_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)
#把元素填充进frame
text_msglist.grid()
text_msg.grid()
button_sendmsg.grid(sticky=E)
#主事件循环
root.mainloop()

以下是运行截图:

希望本文所述对大家的Python程序设计有所帮助

相关文章

pandas 数据实现行间计算的方法

如下所示: ###方法1:用shift函数,不用通过循环 import pandas as pd import numpy as np import matplotlib as p...

python判断一个集合是否包含了另外一个集合中所有项的方法

本文实例讲述了python判断一个集合是否包含了另外一个集合中所有项的方法。分享给大家供大家参考。具体如下: >>> L1 = [1, 2, 3, 3] >&...

使用Python内置的模块与函数进行不同进制的数的转换

使用Python内置的模块与函数进行不同进制的数的转换

binascii 模块: 它包含一个把二进制数值转换成十六进制的函数,同样也可以反过来转。 #binary_value是二进制数值不是字符串,也不是int型的1010 binasci...

使用Python的Twisted框架编写非阻塞程序的代码示例

先来看一段代码: # ~*~ Twisted - A Python tale ~*~ from time import sleep # Hello, I'm a develop...

在Python中使用HTML模版的教程

在Python中使用HTML模版的教程

Web框架把我们从WSGI中拯救出来了。现在,我们只需要不断地编写函数,带上URL,就可以继续Web App的开发了。 但是,Web App不仅仅是处理逻辑,展示给用户的页面也非常重要。...