每次调用函数时,Tkinter scale 都会卡住

Tkinter scale gets stuck each time a function is called

我有一个问题,每当我 运行 一个看似很大的函数时,tkinter Scale 小部件似乎会卡住。

这是代码:

from tkinter import Tk, Button, Frame, Scale

root = Tk()

slider = Scale(root, orient='horizontal')
slider.pack()

frame = Frame(root)
frame.pack()

num = 0


def buttons():
    for widget in frame.winfo_children():
        widget.destroy()

    for i in range(50):
        Button(frame, text='Button' + str(i)).pack()


def basic():
    global num
    slider.set(num)
    num += 1
    print(num)
    if num <= 100:
        slider.after(100, basic)


if __name__ == '__main__':
    buttons()
    basic()

root.bind('<space>', lambda x: buttons())
root.mainloop()

我想让我的程序正常更新滑块,即使我按下 'Space'(意味着调用 buttons() 函数)
如果每次按 Space 时都仔细观察,滑块会卡住一点。
因为我在 Mp3 播放器上使用滑块来显示经过的时间,所以这种时间损失非常重要,例如对于 10 秒左右的音频文件,因为滑块落后很多,看起来好像工作不正常\

我还想指出,销毁按钮然后重新包装对我来说是必要的。
我怀疑发生这种情况是因为程序必须遍历 buttons() 函数,因为它创建了 50 个按钮,所以需要一些时间。还是我记错了?

我可以避免这种延迟吗?

PS:正如我在评论中提到的:

I normally have a button that renames a (button) which is a song and in order for them to alphabetically ordered after renaming i need to recall the function that draws them. If I only configure tha name of the button (and not redraw them), it will stay in place and not move down or up depending on its name, while on the actual directory the order will change leading to inappropriate behavior such as playing the same song

为了更好地理解,这里有一些图片:

提前致谢!

看这段代码:

import tkinter as tk

def config_buttons():
    # Get the `text` of the first button
    starting_value = int(buttons[0].cget("text")) + 1
    # Iterate over all of the buttons
    for i, button in enumerate(buttons, start=starting_value):
        # Change the button's `text` and `command` atributes
        button.config(text=i, command=lambda i=i:print("Clicked %i"%i))

root = tk.Tk()
buttons = []

add_button = tk.Button(root, text="+1 on all buttons", command=config_buttons)
add_button.pack()

for i in range(50):
    button = tk.Button(root, text=i, command=lambda i=i:print("Clicked %i"%i))
    button.pack()
    buttons.append(button)

root.mainloop()

按下 add_button 按钮时,我遍历所有按钮并更改它们的 textcommand 属性。由于我没有创建新按钮,因此该函数运行速度非常快。

您可以在代码中实现类似的功能。基本上,避免创建新按钮,只更新屏幕上已有的按钮。