在tkinter睡觉(Python2)

2024-06-16 11:45:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一张特金特的画布上,在一个小圈子里寻找睡眠。在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函数,但是我不能按我想要的方式增加它。我认为使用多线程是可能的,但必须有一个更简单的解决方案。你知道吗

你知道吗?你知道吗


Tags: tkinterdefcreatebluefillglobalx1x2
1条回答
网友
1楼 · 发布于 2024-06-16 11:45:24

sleep不能与Tkinter很好地混合,因为它会使事件循环停止,从而使窗口锁定,对用户输入没有响应。通常的方法是将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()

相关问题 更多 >