-1

In the following code, the after() method is used on purpose to observe the desired dynamical display of 'label_show'. However, it couldn't display in the correct manner. I would appreciate it if someone guides me along. Note it could run on macOS. A bit correction is necessary on other systems.

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

kafka
  • 129
  • 9
  • Read [While Loop Locks Application](https://stackoverflow.com/questions/28639228/python-while-loop-locks-application) and [Run your own code alongside Tkinter's event loop](https://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop) – stovfl Feb 04 '20 at 09:28
  • 1
    `self.after(5000)` acts like `time.sleep(5)`. Do you want `self.label_show.update_idletasks()` instead. – acw1668 Feb 04 '20 at 09:36
  • 1
    @stovfl:yes, a thread is necessary. and now it works. Thx. – kafka Feb 05 '20 at 03:31

1 Answers1

0

I updated the code by starting a thread as the following:

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

However, if I start the thread in the method rename(), it wont't work either.

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

Could you please explain the subtle difference?

kafka
  • 129
  • 9