Python 特金特:为什么不能';标签小部件是否动态显示?

Python 特金特:为什么不能';标签小部件是否动态显示?,python,tkinter,Python,Tkinter,在下面的代码中,after()方法用于观察“label_show”所需的动态显示。但是,它无法以正确的方式显示。如果有人引导我,我将不胜感激。注意,它可以在macOS上运行。在其他系统上需要进行位校正 import os import time import tkinter as tk from tkinter import filedialog class ReNamer(tk.Tk): def __init__(self): super().__init__()

在下面的代码中,after()方法用于观察“label_show”所需的动态显示。但是,它无法以正确的方式显示。如果有人引导我,我将不胜感激。注意,它可以在macOS上运行。在其他系统上需要进行位校正

import os
import time
import tkinter as tk
from tkinter import filedialog


class ReNamer(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("EasyReNamer V2.0")
        self.n = 0
        label_info = tk.Label(self, text="Please select a folder:")
        label_info.pack()
        panel = tk.Frame()
        btn_rename = tk.Button(panel, text="Click Me", width=10,
                               highlightbackground='orange', command=self.rename)
        btn_rename.grid(row=0, column=0, padx=30)
        btn_check = tk.Button(panel, text="Check", width=10,
                              highlightbackground='darkblue', fg='white')
        btn_check.grid(row=0, column=1, padx=30)
        panel.pack()
        self.label_show = tk.Label(self)
        self.label_show.pack()

    def rename(self):
        folder_path = filedialog.askdirectory(title="EasyReNamer V2.0")
        items_list = os.listdir(folder_path)
        for item in items_list.copy():
            item_path = folder_path + os.sep + item
            if os.path.isdir(item_path) or item.startswith('.') or \
                    item.startswith('~$'):
                continue
            else:
                new_item_path = folder_path + os.sep + '(' + \
                                str(self.n + 1) + ')' + item
                os.rename(item_path, new_item_path)
                self.n += 1

                self.label_show.config(text="{} file(s) renamed".format(self.n))
                self.after(5000)


if __name__ == "__main__":
    root = ReNamer()
    root.mainloop()


我通过如下方式启动线程来更新代码:

# -*-coding:utf-8-*-
"""This is a free tool which easily adds sequence numbers to names of files
in a selected folder, just by clicking your mouse a few times.

Here is the usage:
1. Press the 'Click me' button.
2. Select a folder in the pop-up window.
3. Click 'Choose' to execute the operation or 'Cancel' to give it up.
4. Press 'Check' to make sure the operation has been completed successfully.

Note that operations on hidden files or sub-folders are neglected.
"""
import os
import time
import threading
import tkinter as tk
from tkinter import filedialog


class ReNamer(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("EasyReNamer V2.0")
        self.n = 0
        label_info = tk.Label(self, text="Please select a folder:")
        label_info.pack()
        panel = tk.Frame()
        btn_rename = tk.Button(panel, text="Click Me", width=10,
                               highlightbackground='orange',
                               command=threading.Thread(target=self.rename).start)
        btn_rename.grid(row=0, column=0, padx=30)
        btn_check = tk.Button(panel, text="Check", width=10,
                              highlightbackground='darkblue', fg='white')
        btn_check.grid(row=0, column=1, padx=30)
        panel.pack()
        self.label_show = tk.Label(self)
        self.label_show.pack()

    def rename(self):
        folder_path = filedialog.askdirectory(title="EasyReNamer V2.0")
        items_list = os.listdir(folder_path)
        for item in items_list.copy():

            item_path = folder_path + os.sep + item
            if os.path.isdir(item_path) or item.startswith('.') or \
                    item.startswith('~$'):
                continue
            else:
                new_item_path = folder_path + os.sep + '(' + \
                                str(self.n + 1) + ')' + item
                os.rename(item_path, new_item_path)
                self.n += 1
                print(new_item_path)
                time.sleep(2)
                self.label_show.config(text="{} file(s) renamed".format(self.n))
        print(self.n)
        self.label_show.config(text="{} file(s) completed successfully".format(self.n))


if __name__ == "__main__":
    root = ReNamer()
    root.mainloop()

但是,如果我在方法rename()中启动线程,它也不会工作

# -*-coding:utf-8-*-
"""This is a free tool which easily adds sequence numbers to names of files
in a selected folder, just by clicking your mouse a few times.

Here is the usage:
1. Press the 'Click me' button.
2. Select a folder in the pop-up window.
3. Click 'Choose' to execute the operation or 'Cancel' to give it up.
4. Press 'Check' to make sure the operation has been completed successfully.

Note that operations on hidden files or sub-folders are neglected.
"""
import os
import time
import threading
import tkinter as tk
from tkinter import filedialog


class ReNamer(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("EasyReNamer V2.0")
        self.n = 0
        label_info = tk.Label(self, text="Please select a folder:")
        label_info.pack()
        panel = tk.Frame()
        btn_rename = tk.Button(panel, text="Click Me", width=10,
                               highlightbackground='orange',
                               command=self.rename)
        btn_rename.grid(row=0, column=0, padx=30)
        btn_check = tk.Button(panel, text="Check", width=10,
                              highlightbackground='darkblue', fg='white')
        btn_check.grid(row=0, column=1, padx=30)
        panel.pack()
        self.label_show = tk.Label(self)
        self.label_show.pack()

    def rename(self):
        folder_path = filedialog.askdirectory(title="EasyReNamer V2.0")
        items_list = os.listdir(folder_path)
        thread = threading.Thread(target=self.display)
        thread.start()
        for item in items_list.copy():

            item_path = folder_path + os.sep + item
            if os.path.isdir(item_path) or item.startswith('.') or \
                    item.startswith('~$'):
                continue
            else:
                new_item_path = folder_path + os.sep + '(' + \
                                str(self.n + 1) + ')' + item
                # os.rename(item_path, new_item_path)
                self.n += 1
                print(new_item_path)
                time.sleep(2)
        print(self.n)

    def display(self):
        self.label_show.config(text="{} file(s) renamed".format(self.n))


if __name__ == "__main__":
    root = ReNamer()
    root.mainloop()


你能解释一下细微的区别吗?

阅读和
self.after(5000)
的行为就像
time.sleep(5)
。是否改为
self.label\u show.update\u idletasks()
。@stovfl:是的,需要一个线程。现在它开始工作了。谢谢。