Ubuntu下用Python编写带有GUI的UDP通信终端

环境:Python2.62+Tkinter,Ubuntu

输入对方IP地址和端口就可以进行双方通信,界面仿照IM软件设计。由于UDP监听采用单独线程,TCL/TK库可能不支持,需要自行编译成多线程支持。在Windows下运行正常,窗口大小需要调整一下。

#! /usr/bin/python
from Tkinter import *
import socket
import threading
import tkFont
class Window:
''' main window'''
def __init__(self, master):
self.fm1 = Frame(master)
self.fm1.pack()
#Label(fm1,text='Local IP Address:').grid(row=0,sticky=W,pady=5)
Label(self.fm1, text='Target IP & Port:', font=ft).grid(row=1, sticky=W, pady=5)
Label(self.fm1, text='Message History:', font=ft).grid(row=2, stick=W)
self.ip = StringVar()
self.ip.set('192.168.1.168')
self.port = StringVar()
self.port.set('2345')
self.ipEntry = Entry(self.fm1, width=15, textvariable=self.ip, font=ft)
self.ipEntry.grid(row=1, column=1, sticky=W)
self.portEntry = Entry(self.fm1, textvariable=self.port, font=ft)
self.portEntry.grid(row=1, column=2, sticky=W, pady=5)
self.fm2 = Frame(master)
self.fm2.pack()
self.msgShow = Text(self.fm2, height=12, width=35, font=ft)
self.scroll = Scrollbar(self.fm2, command=self.msgShow.yview)
self.msgShow.configure(yscrollcommand=self.scroll.set)
self.msgShow.pack(side=LEFT, pady=5)
self.scroll.pack(side=RIGHT, fill=Y)
Label(master, text='Write Your Message Below:', font=ft).pack()
self.msgWrite = Text(master, height=3, width=50, font=ft)
self.msgWrite.pack(pady=5)
self.msgWrite.focus_set()
self.msgWrite.bind('<Control-Return>', self.sendmsg)
Label(root, text='Press Ctrl+Enter to Send Message', font=ft).pack(side=BOTTOM)
def sendmsg(self, event=None):
self.msg = self.msgWrite.get(1.0, END)
self.msgShow.insert(END, 'Send: ' + self.msg)
self.msgShow.see(END)
self.msgWrite.delete(1.0, END)
mysocket.sendto(self.msg, (self.ipEntry.get(), int(self.portEntry.get())))
return 'break'# Grate idea!
class Listenthread(threading.Thread):
'''TCL/TK multithreading support is needed'''
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while True:
data = mysocket.recv(512)
window.msgShow.insert(END, 'Recv: ' + data)
root = Tk()
ft = tkFont.Font(family='Serif', size=12, weight=tkFont.NORMAL)
root.title('UDP test')
root.geometry('270x350')
window = Window(root)
mysocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mysocket.bind(('', int(window.portEntry.get())))
lt = Listenthread()
lt.setDaemon(True)
lt.start()
root.mainloop()

liuxiao216囧gmail.com  原创内容,转载请注明作者,出处。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwpsxp.html