简体   繁体   中英

Why is threading not showing Tkinter window?

I wrote some code while learning to use Tkinter and when i attempted to thread it, it did not show the window however when it runs just the main loop it does.

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

It seems to be a problem with the text widget but i don't know what is wrong with it. When i remove the insert line, the box appears with trheading but with that line, it does not appear. What is the problem with it?

I think your problem is that you are initialising Tkinter on the mainthread and then invoking the Chat frame (which uses root from the mainthread) on the background thread. I expected this might cause some problems. Without having much knowledge of the internals I decided to test this theory out by writing your code slightly differently. I have re-written your code so the initialisation of root and Chat is on the same thread and it does the trick.

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

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM