这是我的第一篇文章,所以如果我做错了什么,请耐心等待。
我正在开发一个非常简单的聊天程序,用python编写,有一个gtk接口,一个用户拥有服务器,另一个用户拥有客户端。一切正常,除了我不能发送或接收消息(尽管连接已建立)。我已经在论坛上找到了解决办法,但是我没有找到任何东西。
(部分)GUI的代码是:
gi.require_version ('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject, GLib
class GUI:
def __init__ (self, is_server):
GObject.threads_init ()
[...]
self.buffer1 = Gtk.TextBuffer ()
self.text_box = Gtk.TextView (buffer=self.buffer1)
self.text_box.set_editable (False)
[...]
self.th = threading.Thread (target = self.receive)
self.th.daemon = True
self.th.start ()
Gtk.main ()
def receive (self):
while (True):
try:
msg = self.socket.receive_message ()
if (msg != ""): self.insert_text (msg)
except: pass
def insert_text (self, text):
self.text_box.set_editable (True)
end_iter = self.buffer1.get_end_iter ()
try: self.buffer1.insert (end_iter, text + "\n")
except: pass
self.text_box.set_editable (False)
adj = self.scr.get_vadjustment ()
adj.set_value (adj.get_upper ())
在客户端.py或者服务器.py(是相同的行):
^{pr2}$我收到的错误是:
(Chat.py:61330): Gdk-ERROR **: The program 'Chat.py' received an X Window System error.
This probably reflects a bug in the program.
The error was 'BadRequest (invalid request code or no such operation)'.
(Details: rerial 892 error_code 1 request_code 0 (core protocol) minor_code 0)
(Note to programmers: normally, X errors are reported asynchronously;
that is, you will receive the error a while after causing it.
To debug your program, run it with the GDK_SYNCHRONIZE environment
variable to change this behavior. You can get a meaningful
backtrace from your debugger if you break on the gdk_x_error() function.)
Trace/BPT trap (code dumped)
我认为这是一个多线程错误,因为在第二个线程中,我试图更改Gtk.text视图但我不太确定(我对多线程很陌生)。在
感谢大家。在
不能从调用
Gtk.main()
的线程调用GTK+函数。您必须更改线程以将数据发送到主线程,并让主线程修改GUI,例如,将对receive()
中的insert_text()
的调用包装在GLib.idle_add()
中。在相关问题 更多 >
编程相关推荐