[英]Sleep in tkinter (python2)
我试图在tkinter的画布上的while循环中入睡。 在Python2中,目标是要有一个随机的移动点,每X秒钟刷新一次(然后,我将可以有一个更大的脚本来精确执行所需的操作),而无需任何外部用户输入。
现在,我做了这个:
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")
fen1 = Tkinter.Tk()
can1 = Tkinter.Canvas(fen1, height=200, width=200)
affichage()
can1.pack()
temps = 3000
while True:
can1.after(temps, affichage2)
x1 += 10
y1 += 10
x2 += 10
y2 += 10
temps += 1000
fen1.mainloop()
fen1.destroy()
(对不起的法语变量名称是:°)因此,我尝试使用.after函数,但是无法按需增加它。 我认为使用多线程是可能的,但是必须有一个更简单的解决方案。
你有什么主意吗 ?
sleep
与Tkinter不能很好地融合在一起,因为它会使事件循环暂停,从而使窗口锁定并变得对用户输入无响应。 每隔X秒使某事发生的通常方法是将after
调用放入要传递给after
函数中。 尝试:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.