[英]How can I run a Python GTK GUI and a chat at the same time?
Can someone help me with Python GTK + sockets?有人可以帮我解决 Python GTK + sockets 吗? I'm trying to make a chat, so I'm running this to receive messages from other users:我正在尝试聊天,所以我正在运行它来接收来自其他用户的消息:
def socket_recv(socket, buffer):
while True:
try:
message = socket.recv(1024).decode()
end_iter = buffer.get_end_iter()
buffer.insert(end_iter, message + "\n")
while Gtk.events_pending():
Gtk.main_iteration()
except:
print("Você foi desconectado do servidor")
socket.close()
break
and in my main, I am trying to run this event:在我的主要,我正在尝试举办这个活动:
def onConnect(self, widget):
self.nickname = self.nickname_entry.get_text().strip()
self.adress = self.adress_entry.get_text().strip()
if self.nickname == "" or self.adress == "":
self.error_message.show()
return
HOST, PORT = self.adress.split(':')
PORT = int(PORT)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((HOST, PORT))
self.sock.send(str.encode(self.nickname))
self.builder.add_from_file("interface.glade")
self.builder.connect_signals(self)
self.chat_text.set_editable(False)
self.chat_text.set_wrap_mode(3)
self.chat_buffer = self.chat_text.get_buffer()
self.chat_buffer.set_text("Início do chat\n")
self.end_iter = self.chat_buffer.get_end_iter()
self.chatWindow.show()
while Gtk.events_pending():
Gtk.main_iteration()
thread = threading.Thread(target=socket_recv(self.sock, self.chat_buffer))
thread.start()
I get the adress and nickname of the user in the starting window of the GUI, and then try to connect to the server after they click on the button "Connect", then the chat window appear.我在GUI的起始window中得到用户的地址和昵称,然后在他们点击“连接”按钮后尝试连接服务器,然后出现聊天window。 Although I can connect to the server, when I try to run my chat GUI with the socket_recv, the GUI becomes completely nonfunctional (buttons cant be pressed, etc.) and I have to force quit to close the application.虽然我可以连接到服务器,但当我尝试使用 socket_recv 运行我的聊天 GUI 时,GUI 变得完全不起作用(无法按下按钮等),我必须强制退出以关闭应用程序。 I'm pretty new to Python, GTK and threading, and would appreciate any help我对 Python、GTK 和线程非常陌生,希望有任何帮助
Problem solved guys, I just changed问题解决了,我只是改变了
threading.Thread(target=socket_recv(self.sock, self.chat_buffer))
to至
thread = threading.Thread(target=socket_recv, args=(self.sock, self.chat_buffer))
Sorry for any inconvenience任何不便敬请谅解
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.