【问题标题】:Lagging instead of executing a tkinter for-loop using arrays滞后而不是使用数组执行 tkinter for 循环
【发布时间】:2018-04-19 15:09:40
【问题描述】:

我正在尝试使用 colors 中的颜色为“圆形”爆炸设置动画,但每当我运行它时,它就会冻结并且什么也不做。

谢谢!

from tkinter import *
from random import *
from time import *
from math import *

space = Tk()
s = Canvas(space, height = 1000, width = 1000, background = "light blue")
s.pack()


##EXPLOSION

xE = 375
yE = 475

x = []
y = []
r = []

rSpd = []

eAngle = []

xAr = []
yAr = []

colors = []
drawing = []
sleep(1)
cakeE = 500
colors = ["#EA7FF0","#E44FEE","#87078F","#F9DBFB","#F7B8FB","gray76","grey","white"]
for i in range( cakeE ):                                       
    x.append( xE )
    y.append( yE )

    xAr.append( randint(1, 3) )
    yAr.append( randint(1, 3) )

    r.append( 0 )
    rSpd.append(0)

    eAngle.append( uniform(1,15) )
    eAngle.append( uniform(0, 2*pi) )

    drawing.append(0)
    colors.append( choice(colors) )
for f in range(400):                                                 

    for i in range(cakeE):

        drawing[i] = s.create_rectangle( x[i], y[i], x[i] + xAr[i], y[i]\
                                         + yAr[i], fill = colors[i] )

        x[i] = xE + r[i] * cos( eAngle[i] )
        y[i] = yE - r[i] * sin( eAngle[i] )

        r[i] = r[i] + rSpd[i]
        eAngle[i] = eAngle[i]+0.01

【问题讨论】:

  • 你发布的代码太多了。请尝试将其减少到minimal reproducible example
  • 这可能是sleep()引起的。在 tkinter 中,您不想使用 sleep,因为它会导致应用程序冻结。而是合并after()
  • @Mike-SMT "NameError: name 'after' 未定义"。你会怎么做呢?
  • 在 tkinter 中查找 after() 的使用。您需要指定一些东西来“跟踪”时间。例如,您可以使用space 的根窗口,并且您需要提供一个函数在时间结束后调用。 space.after(1000, some_func_name)。请记住 1000 = 1 秒。

标签: python arrays python-3.x tkinter tkinter-canvas


【解决方案1】:

使用您提供的代码(不是 MCVE)很难解决这个问题。 然而,这里有一个使用 after() 的示例,向您展示它是如何使用的。此示例应该足以让您将 sleep() 替换为 after() 请记住,您可能需要将一些代码移动到函数中才能正常工作。

from tkinter import *


space = Tk()
lbl = Label(space, text="Before timed event.")
lbl.pack()

def do_something():
    global lbl
    lbl.config(text="After timed event.")
    # execute some code here

# set a 3 second timer to activate the do something function.       
space.after(3000, do_something)

space.mainloop()

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    相关资源
    最近更新 更多