2017-05-29 102 views
0


這是我的第一篇文章,所以如果我做錯了,請耐心等待。
我正在使用gtk界面用python編寫的一個非常簡單的聊天程序,一個用戶有服務器,另一個有客戶端。除了我無法發送或接收消息(儘管連接已建立),所有工作都正常。我已經在論壇上尋找解決方案,但我沒有找到任何東西。
用於GUI的代碼(的部分)是:
Python gui中的Gdk-ERROR與多線程

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()) 

而在Client.py或Server.py(是相同的行):

class Client/Server: 
    [...] 
    def receive_message (self): 
     try: 
      msg0 = self.conn.recv (1024) 
      msg = msg0.decode ("utf-8") 
      return msg 
     except: pass 

我收到的錯誤是:

(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.TextView的文本,但我不知道(我與MUL很新tithreading)。

感謝所有。

回答

1

您不能從調用Gtk.main()以外的線程調用GTK +函數。您必須更改自己的線程以將數據發送到主線程,並修改GUI,例如通過在的GLib.idle_add()中將呼叫打包爲insert_text()

+0

它的工作,非常感謝。 – Momolo