Tkinter and thread. out of stack space (infinite loop?)

前端 未结 2 893
耶瑟儿~
耶瑟儿~ 2021-01-18 09:07

I\'m experimenting with Tkinter and the threads mechanism. Can anyone explain why this raises the exception:

 out of stack         


        
2条回答
  •  猫巷女王i
    2021-01-18 09:08

    You have a couple of fatal flaws in your code. For one, you simply can't write code that touches tkinter widgets from more than one thread. You are creating the root window in the main thread, so you can only ever directly access widgets from the main thread. Tkinter is not thread safe.

    The second problem is that you have an infinite loop that is constantly appending to the text widget. It has no choice but to eventually run out of memory.

    To solve your problem you should:

    1. not have an infinite loop that forever appends to the text widget
    2. not access any widgets from more than a single thread

    If you want to run a function once a second, there are better ways to do that than with threads. In short:

    def do_every_second():
        cont.insert("end", str(n) + "\n")
        root.after(1000, do_every_second)
    

    This will cause do_every_second to do whatever it does, then arranges for itself to be called again one second in the future.

提交回复
热议问题