且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 tkinter (python2) 中睡觉

更新时间:2022-06-20 18:35:25

sleep 与 Tkinter 不能很好地混合,因为它使事件循环停止,从而使窗口锁定并变得无响应到用户输入.使某事每 X 秒发生一次的通常方法是将 after 调用放在您传递给 after 的函数中.试试:

sleep does not mix well with Tkinter because it makes the event loop halt, which in turn makes the window lock up and become unresponsive to user input. The usual way to make something happen every X seconds is to put the after call inside the very function you're passing to after. Try:

import Tkinter, time

x1, y1, x2, y2 = 10, 10, 10, 10
def affichage():
    global x1, y1, x2, y2
    can1.create_rectangle(x1, y1, x2, y2, fill="blue", outline="blue")
def affichage2():
    global x1, y1, x2, y2
    can1.delete("all")
    can1.create_rectangle(x1, y1, x2, y2, fill="blue", outline="blue")
    x1 += 10
    y1 += 10
    x2 += 10
    y2 += 10
    can1.after(1000, affichage2)

fen1 = Tkinter.Tk()
can1 = Tkinter.Canvas(fen1, height=200, width=200)
affichage()
can1.pack()
temps = 3000

can1.after(1000, affichage2)
fen1.mainloop()

fen1.destroy()