UI Left EXE Right Recive TCPIP

发布于:2024-12-07 ⋅ 阅读:(36) ⋅ 点赞:(0)

import tkinter as tk
from tkinter import messagebox, filedialog
from tkinter import ttk
import socket
import threading
import subprocess
import time
from datetime import datetime
from PIL import Image, ImageTk

# 全局变量
client_socket = None
connected = False

def connect_to_server():
    global client_socket, connected
    ip = "127.0.0.1"
    port = 7930
    
    try:
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client_socket.connect((ip, port))
        connected = True
        status_indicator.config(bg='green')
        messagebox.showinfo("Success", f"Connected to server at {ip}:{port}")
        
        # Start a new thread to receive data
        threading.Thread(target=receive_data).start()
    except Exception as e:
        connected = False
        status_indicator.config(bg='red')
        messagebox.showerror("Error", f"Failed to connect to server: {e}")

def disconnect_from_server():
    global client_socket, connected
    if connected:
        client_socket.close()
        connected = False
        status_indicator.config(bg='red')
        messagebox.showinfo("Disconnected", "Disconnected from server")

def receive_data():
    while connected:
        try:
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                break
            current_time = datetime.now().strftime("%H:%M:%S")
            received_data_text.insert(tk.END, f"[{current_time}] {data}\n")
            received_data_text.yview_moveto(1)  # Scroll to the bottom
        except Exception as e:
            print(f"Error receiving data: {e}")
            break
    disconnect_from_server()

def launch_application():
    app_path = r"D:\aa\Public_Release\aa.exe"
    try:
        subprocess.Popen(app_path)
    except Exception as e:
        messagebox.showerror("Error", f"Failed to launch application: {e}")

# 创建主窗口
root = tk.Tk()
root.title("TCP Client")
root.geometry("800x600")

# 连接状态指示器(右上角)
status_indicator = tk.Frame(root, width=100, height=100, bg='red')
status_indicator.place(x=700, y=0)

# 左侧区域 - 启动应用程序按钮
left_frame = tk.Frame(root, width=800, height=300)
left_frame.pack(side=tk.TOP, fill=tk.X)

# 加载并设置图像
image_path = r"C:\Users\Administrator\Desktop\Study\i.png"  # 替换为实际图像路径
try:
    image = Image.open(image_path)
    image = image.resize((150, 150), Image.Resampling.LANCZOS)
    img = ImageTk.PhotoImage(image)
except IOError:
    img = None

launch_button = tk.Button(left_frame, image=img, command=launch_application)
if img:
    launch_button.image = img  # Keep a reference!
launch_button.pack(pady=125)

# 右侧区域 - 显示接收到的数据
right_frame = tk.Frame(root, width=800, height=300)
right_frame.pack(side=tk.TOP, fill=tk.X)

received_data_label = tk.Label(right_frame, text="Received Data:")
received_data_label.pack(pady=10)

received_data_text = tk.Text(right_frame, wrap=tk.WORD, height=15, width=60)
received_data_text.pack(padx=10, pady=10)

# 控制按钮
control_frame = tk.Frame(root)
control_frame.pack(pady=10)

connect_button = tk.Button(control_frame, text="Connect", command=connect_to_server)
connect_button.grid(row=0, column=0, padx=5)

disconnect_button = tk.Button(control_frame, text="Disconnect", command=disconnect_from_server)
disconnect_button.grid(row=0, column=1, padx=5)

# 初始化全局变量
client_socket = None
connected = False

# 运行主循环
root.mainloop()


网站公告

今日签到

点亮在社区的每一天
去签到