在 tkinter (python2) 中睡觉 [英] Sleep in tkinter (python2)

查看:41
本文介绍了在 tkinter (python2) 中睡觉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 tkinter 的画布中寻找在 while 循环中睡眠.在 Python2 中目标是有一个随机移动的点,每 X 秒刷新一次(然后.我将能够使用更大的脚本来精确地制作我想要的东西),而无需任何外部用户输入.

I search to make a sleep in a while loop, in an tkinter's canvas. In Python2 The aim is to have a randomly moving point, refreshed every X seconds (then .I'll be able a bigger script to make what I want precisely), without any external user input.

现在,我做了这个:

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

(sorry for the french variable names :°) So, I tried with the .after function, but I can't increase it how I want. I think it could be possible with multithreading, but there must be an easier solution.

你有什么想法吗?

推荐答案

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()

这篇关于在 tkinter (python2) 中睡觉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆