睡在tkinter(python2)

时间:2016-07-12 17:11:31

标签: python tkinter

我在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函数,但我不能按照我想要的方式增加它。我认为多线程可以实现,但必须有一个更简单的解决方案。

你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

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()
相关问题