我正在为我的网络课程开发一个项目,教授设计了一个游戏,通过发送用户数据并让客户端发回字节,通过套接字与客户端进行交互。我被选中在python中做客户端,我选择了tkinter作为客户端的GUI并且它到目前为止一直很好但是为了保持从服务器线程接收消息的cilent需要运行GUI并从套接字接收连续地进行。
from tkinter import *
import tkinter.simpledialog
from sys import exit
from struct import *
from socket import *
from threading import Thread
import tkinter.scrolledtext as tkst
skt = socket(AF_INET, SOCK_STREAM)
skt.connect(("hostname.com", 5190))
msg = skt.recv(1024)
userEntry = object
def start_func():
def create_func():
name = tkinter.simpledialog.askstring('askstring', 'Enter Name')
flag = tkinter.simpledialog.askstring('askstring', 'Enter Flag')
attack = tkinter.simpledialog.askstring('askstring', 'Enter Attack')
defense = tkinter.simpledialog.askstring('askstring', 'Enter Defense')
regen = tkinter.simpledialog.askstring('askstring', 'Enter Regeneration')
Health = tkinter.simpledialog.askstring('askstring', 'Enter Health')
Gold = tkinter.simpledialog.askstring('askstring', 'Enter Gold')
Current_room = tkinter.simpledialog.askstring('askstring', 'Current Room')
Description_len = tkinter.simpledialog.askstring('askstring', 'Enter descrition length')
Description = tkinter.simpledialog.askstring('askstring', 'Enter description')
def change_func():
def fight_func():
def pvp_func():
def loot_func():
def leave_func():
def submit_value():
class TestClient(Frame):
def __init__(self, master):
global userEntry
Frame.__init__(self, master)
self.pack()
for n in range(3):
self.grid_rowconfigure(n, weight=1)
for n in range(8):
self.grid_columnconfigure(n, weight=1)
t1 = tkst.ScrolledText(self,wrap = WORD, width=80)
t1.grid(row=0, column=0, columnspan=8)
t1.insert(INSERT,(skt.recv(500).decode("utf-8")))
la1 = Label(self, text="Value entry:")
la1.grid(row=1, column=0)
userEntry = StringVar()
global e1
e1 = Entry(self, width=40, textvariable=userEntry)
e1.grid(row=1, column=1, columnspan=6)
e2 = Button(self, text="Enter", command=submit_value)
e1.delete(0, END)
e2.grid(row=1, column=5, columnspan=10)
b1 = Button(self, text="Start", width=10,padx=10,pady=10, command=start_func)
b1.grid(row=2, column=0)
b0 = Button(self, text="Create Character", width=10,padx=10,pady=10, command=create_func)
b0.grid(row=2, column=1)
b2 = Button(self, text="Change Room", width=10,padx=10,pady=10, command=change_func)
b2.grid(row=2, column=3)
b3 = Button(self, text="FIGHT", width=10,padx=10,pady=10, command=fight_func)
b3.grid(row=2, column=4)
b4 = Button(self, text="PvP FIGHT", width=10,padx=10,pady=10, command=pvp_func)
b4.grid(row=2, column=5)
b5 = Button(self, text="Loot", width=10,padx=10,pady=10, command=loot_func)
b5.grid(row=2, column=6)
b6 = Button(self, text="Leave", width=10,padx=10,pady=10, command=leave_func)
b6.grid(row=2, column=7)
root = Tk()
tw = TestClient(root)
root.mainloop()
现在这是我的客户端,按钮功能目前没有做任何事情,因为我仍然在弄清楚如何将消息编码为二进制,我现在最麻烦的是线程。在我上大学的时候,我没有使用过很多线程,而且我在python课程中对它进行了轻微的介绍。
我试图在tkinter中搜索线程,但我找到的所有内容都与我的客户端完全不同,我无法将其改编为我的,所以有些人帮助添加线程到这个客户端,让GUI文本小部件不断从服务器接收它将被appriciated的数据。