Python-Tkinter在fram中使用after方法和cotroll

2024-09-28 22:31:09 发布

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

是否可以在fps中使用.after()-方法而不是定义毫秒。所以我想要一个6帧(60赫兹)的标签。 -->;根。后(6) 而不是用毫秒来定义时间

例如:

root = tk.Tk()

ListofStimuli = ["\u00B6","\u0126"]

labelprint = tk.Label(root,text="+", font = ('Sans','80','bold'), bg = "white")
labelprint.place(relx=.5, rely=.5, anchor="c")


for elem in ListofStimuli:

    labelprint.config(text=elem) 
    root.after(100, lambda: var.set(0))
    root.wait_variable(var)

Tags: 方法textgt定义var时间root标签
1条回答
网友
1楼 · 发布于 2024-09-28 22:31:09

That being said, you can do whatever math you want to try to accommodate for variances. – Bryan Oakley

按照这一思路,保留循环的运行时间列表;然后从首选的UI刷新率中减去平均刷新率。在纳米尺度上迭代地向首选刷新率移动,以解释时序不规则性。在

这将在大约1秒内达到并保持1ms精度,这与after()方法允许的精度一样精确,给定的输入是milleseconds的整数。这种方法适用于任何最小到千分之一秒的刻度。在

import time
import tkinter as tk

UI_REFRESH = 100 # your preferred refresh rate in milleseconds
UI_DELTA = 0.000001 # nanosecond scale iterative filter step size
UI_DEPTH = 10 # depth of ui_refreshes moving average

def animate():

    global last_refresh, ui_refreshes, last_refresh, ui_delta

    print("\033c") # clear terminal    
    # keep moving average of UI_REFRESH timing
    now = time.time()
    ui_refreshes.append(now - last_refresh)
    ui_refreshes = ui_refreshes[-UI_DEPTH:]
    ui_refresh = sum(ui_refreshes) / len(ui_refreshes)
    last_refresh = now

    # filter nanosecond scale timing oddities iteratively
    # both as they arise due to load and between various systems
    refresh_error = abs(UI_REFRESH_SEC-ui_refresh)
    if float('%.5f' % ui_refresh) < (UI_REFRESH_SEC):
        ui_delta += UI_DELTA
    if float('%.5f' % ui_refresh) > (UI_REFRESH_SEC):
        ui_delta -= UI_DELTA

    # do whatever your loop does
    # note this must take less time than your refresh rate!!
    print(  int(time.time()),
            ('%.6f' % ui_refresh),
            ('%.6f' % refresh_error),
            ('%.4f' % round(ui_refresh, 4)),
            int(1000*round(ui_refresh, 4)))

    # set perfect UI_REFRESH timing
    pause = int(1000 *
                min(UI_REFRESH_SEC, (
                    max(0, (
                        2 * UI_REFRESH_SEC - ui_refresh + ui_delta)))))
    master.after(pause, animate)

print("\033c") # clear terminal
UI_REFRESH_SEC = UI_REFRESH/1000
ui_refreshes = []
last_refresh = time.time()
ui_delta = 0
master = tk.Tk()
master.after(0, animate)
master.mainloop()

相关问题 更多 >