请用python为这个代码补充一个GUI界面,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 20:02:12 浏览: 72
这里是一个简单的GUI界面示例,你可以根据自己的需求进行修改和优化:
```python
import time
import socket
import tkinter as tk
class ChatGUI:
def __init__(self, master):
self.master = master
master.title("Chat")
self.label_ip = tk.Label(master, text="IP:")
self.label_ip.grid(row=0, column=0, padx=5, pady=5)
self.entry_ip = tk.Entry(master)
self.entry_ip.grid(row=0, column=1, padx=5, pady=5)
self.label_port = tk.Label(master, text="Port:")
self.label_port.grid(row=1, column=0, padx=5, pady=5)
self.entry_port = tk.Entry(master)
self.entry_port.grid(row=1, column=1, padx=5, pady=5)
self.label_send = tk.Label(master, text="Send:")
self.label_send.grid(row=2, column=0, padx=5, pady=5)
self.entry_send = tk.Entry(master)
self.entry_send.grid(row=2, column=1, padx=5, pady=5)
self.button_send = tk.Button(master, text="Send", command=self.send_message)
self.button_send.grid(row=3, column=0, padx=5, pady=5)
self.button_quit = tk.Button(master, text="Quit", command=self.quit)
self.button_quit.grid(row=3, column=1, padx=5, pady=5)
self.textbox = tk.Text(master)
self.textbox.grid(row=4, column=0, columnspan=2, padx=5, pady=5)
self.ip = ""
self.port = 0
self.other_addr = None
self.byte = 1024
self.udp_socket = None
def send_message(self):
if not self.udp_socket:
self.ip = self.entry_ip.get()
self.port = int(self.entry_port.get())
self.other_addr = (self.ip, self.port)
self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
send_data = self.entry_send.get().encode("utf-8")
self.udp_socket.sendto(send_data, self.other_addr)
self.textbox.insert(tk.END, "Sent to %s: %s\n" % (self.other_addr, send_data.decode("utf-8")))
rev_data, other_addr = self.udp_socket.recvfrom(self.byte)
localTime = time.asctime(time.localtime(time.time()))
self.textbox.insert(tk.END, "%s Received from %s: %s\n" % (localTime, other_addr, rev_data.decode("utf-8")))
def quit(self):
if self.udp_socket:
self.udp_socket.close()
self.master.quit()
if __name__ == "__main__":
root = tk.Tk()
gui = ChatGUI(root)
root.mainloop()
```
在这个示例中,我们创建了一个名为`ChatGUI`的类,它继承自`tkinter.Tk`类。在`ChatGUI`类的构造函数中,我们创建了界面元素(如标签、文本框、按钮等),并将它们按照网格布局放置在窗口上。
当用户点击“Send”按钮时,我们将获取IP地址、端口号和发送的消息,并使用UDP套接字发送消息。然后,我们等待接收来自对方的回复,并向文本框添加发送和接收消息的日志。当用户点击“Quit”按钮时,我们将关闭UDP套接字并退出应用程序。
你可以在代码中添加一些错误处理程序,以确保应用程序在发生错误时能够正确地恢复。此外,你也可以使用其他的布局管理器(如包装器、网格布局、框架等)来调整界面布局。
阅读全文