我试图在 Python3 中向基于套接字的通信器添加图形界面
import sys
import socket
import select
from tkinter import *
def chat_client():
# initialize GUI
window = Tk()
window.geometry("600x800")
window.title("Communicator")
w = Canvas(window, width=580, height=450, bg="ivory2")
w.place(x=5, y=300)
# whole conversation is stored here
conversation = Text(window, width=80, height=30, wrap=WORD)
conversation.place(x=10, y=310)
label_enter = Label(window, text="Enter message: ")
label_enter.place(x=5, y=20)
# the message from here is being taken to send / write on std out
message_entry = Entry(window, width=30)
message_entry.place(x=120, y=20)
msg = ""
def say():
x = message_entry.get()
sys.stdout.write(x)
conversation.insert(0.0, x + '\n')
msg = message_entry.get().encode()
message_entry.delete(0, 'end')
btn_send = Button(window, text="Send!", command=say).place(x=120, y=50)
#THIS SEEMS TO BE THE PROBLEM!!!
window.mainloop()
######################
host = 'localhost'
port = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try:
s.connect((host, port))
except:
print('Unable to connect')
sys.exit()
print('Connected to remote host. You can start sending messages')
#sys.stdout.write('[Me] ')
sys.stdout.flush()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
ready_to_read, ready_to_write, in_error = select.select(socket_list, [], [], 1)
for sock in ready_to_read:
if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
if not data:
print('\nDisconnected from chat server')
sys.exit()
else:
# print data
sys.stdout.write(str(data))
#conversation.insert(0.0, str(data) + '\n')
sys.stdout.write('\n-> ');
sys.stdout.flush()
else:
# user entered a message
#msg = message_entry.get().encode() #sys.stdin.readline().encode()
s.send(msg.encode())
msg2 = sys.stdin.readline().encode()
s.send(msg2)
sys.stdout.write('\n-> ');
sys.stdout.flush()
message_entry.delete(0, 'end')
if __name__ == "__main__":
sys.exit(chat_client())
我正在使用这个服务器(工作正常)。我认为问题在于 Tkinter mainloop() 函数(第 39 行)。我把它搬到了很多不同的地方,似乎没有任何效果。如果没有 Tkinter 窗口,它工作得很好顺便说一句,当我在没有 tkinter 的情况下打开这个通信器的 2 个实例时,正在发送和接收消息,而没有 tkinter。请帮忙,我的想法不多了。PS 抱歉我的英语不好,这不是我的第一语言(Python 也不是)。