tkinter root.mainloop with While True loop

前端 未结 2 2047
渐次进展
渐次进展 2020-12-18 15:41

I am using tkinter to display some labels based on voltages I am reading. However, it stops executing after one read. I have found that it is due to root.mainloop(). But I a

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 16:01

    Tkinter needs mainloop to work (to call all functions behind).
    Use root.after(time_ms, function_name_without_() ) (before mainloop)
    to run some function - and that function have to run the same after(...) to work in loop.

    In Tkinter you don't use while True because while True is to make (main)loop
    but Tkinter has own mainloop.

    And don't use sleep() - use after()

    Put all code from while True (except mainloop) in some function and call it using after().
    Use second after() in place of sleep().

    import Tkinter as tk
    
    master = tk.Tk()
    
    def my_mainloop():
        print "Hello World!"
        master.after(1000, my_mainloop)    
    
    master.after(1000, my_mainloop)
    
    master.mainloop()
    

提交回复
热议问题