2016-03-01 60 views
0

我在學習使用Tkinter的同時編寫了一些代碼,當我嘗試對它進行線程化時,它並沒有顯示窗口,但是當它運行它的主循環時卻沒有顯示。爲什麼線程不顯示Tkinter窗口?

import socket,threading,time 
from Tkinter import * 

class Chat(Frame): 
    def __init__(self,root): 
     Frame.__init__(self,root) 
     self.text=Text(self, bg='black', fg='white') 
     self.text.configure(state=DISABLED) 
     self.text.configure(state=NORMAL) 
     self.text.insert(END, 'hello\n'*40) 
     self.text.configure(state=DISABLED) 
     self.text.pack() 

def main(): 
    root=Tk() 
    root.configure(background='black') 
    c=Chat(root) 
    c.pack() 
    root.mainloop() 
    #t=threading.Thread(target=root.mainloop) 
    #t.start() 


if __name__=='__main__': 
    main() 

這似乎是與文本小部件的問題,但我不知道它是什麼問題。當我刪除插入行,該框出現trheading但該行,它不會出現。它有什麼問題?

+0

在新線程中究竟想做什麼? – cdonts

+0

@crest我想將主循環作爲一個線程來啓動,這樣我可以讓程序在tkinter窗口啓動時執行其他操作。 –

+0

相反,您應該在主線程中運行主循環,並在程序需要執行其他操作時啓動新線程。 – cdonts

回答

0

我認爲你的問題是你正在初始化主線程上的Tkinter,然後在後臺線程上調用Chat幀(它使用來自mainthread的根)。我預計這可能會導致一些問題。在不瞭解內部知識的情況下,我決定用略微不同的方式編寫代碼來測試這個理論。我已經重新編寫了你的​​代碼,所以和Chat的初始化在同一個線程上,它的確有用。

import threading 
from Tkinter import * 

class Chat(Frame): 
    def __init__(self,root): 
     Frame.__init__(self,root) 
     self.text=Text(self, bg='black', fg='white') 
     self.text.configure(state=DISABLED) 
     self.text.configure(state=NORMAL) 
     self.text.insert(END, 'hello\n'*40) 
     self.text.configure(state=DISABLED) 
     self.text.pack() 

def run(): 
    root=Tk() 
    root.configure(background='black') 
    c=Chat(root) 
    c.pack() 
    root.mainloop() 

def main(): 
    t=threading.Thread(target=run) 
    t.start() 
    t.join() 


if __name__=='__main__': 
    main() 

希望有幫助。

相關問題