Tkinter: почему виджет Label не может отображаться динамически? - PullRequest
0 голосов
/ 04 февраля 2020

В следующем коде метод 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()

1 Ответ

0 голосов
/ 05 февраля 2020

Я обновил код, запустив поток следующим образом:

# -*-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()

Не могли бы вы объяснить тонкую разницу?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...