用python为下面代码实现GUI,要求:仅实现类似聊天框功能即可,ip地址和port在代码中写入不能更改。代码:import time import socket #import tk def main(): ip = "172.20.10.13" port = 8888 other_addr = (ip, port) byte = 1024 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: send_data = input("发送给客户端:").encode("utf-8") udp_socket.sendto(send_data, other_addr) #输入数据为空退出,否则进入接收状态 if send_data: rev_data, other_addr = udp_socket.recvfrom(byte) localTime = time.asctime(time.localtime(time.time())) print(localTime,"收到来自%s的信息: %s" % (other_addr, rev_data.decode("utf-8"))) else: break udp_socket.close() if __name__ == '__main__': main()
时间: 2023-12-17 11:05:00 浏览: 82
以下是使用Python tkinter模块实现的GUI代码,实现了类似聊天框的功能:
```python
import time
import socket
import tkinter as tk
# 创建GUI窗口
root = tk.Tk()
root.title('UDP聊天')
root.geometry('400x400')
# 创建文本框和滚动条
text = tk.Text(root)
text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 将文本框和滚动条关联
text.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=text.yview)
# 创建输入框和发送按钮
input_frame = tk.Frame(root)
input_frame.pack(side=tk.BOTTOM, fill=tk.X)
input_entry = tk.Entry(input_frame)
input_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
send_button = tk.Button(input_frame, text='发送')
send_button.pack(side=tk.RIGHT)
# 设置UDP通信参数
ip = "172.20.10.13"
port = 8888
other_addr = (ip, port)
byte = 1024
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 定义发送函数
def send_msg():
send_data = input_entry.get().encode("utf-8")
udp_socket.sendto(send_data, other_addr)
localTime = time.asctime(time.localtime(time.time()))
text.insert(tk.END, localTime + ' 发送给客户端: ' + input_entry.get() + '\n')
input_entry.delete(0, tk.END)
# 定义接收函数
def recv_msg():
rev_data, other_addr = udp_socket.recvfrom(byte)
localTime = time.asctime(time.localtime(time.time()))
text.insert(tk.END, localTime + ' 收到来自%s的信息: %s \n' % (other_addr, rev_data.decode("utf-8")))
# 设置窗口关闭函数
def close_window():
udp_socket.close()
root.destroy()
# 绑定发送按钮和发送函数
send_button.config(command=send_msg)
# 接收消息并插入到文本框中
root.after(100, recv_msg)
# 启动GUI程序
root.protocol('WM_DELETE_WINDOW', close_window)
root.mainloop()
```
运行该代码会弹出一个窗口,可以在输入框中输入消息并点击发送按钮发送消息,接收到的消息会显示在文本框中。同时,程序会持续接收UDP消息并自动更新到文本框中。点击窗口右上角的关闭按钮会关闭UDP连接并退出程序。
阅读全文