【发布时间】:2020-01-22 07:38:34
【问题描述】:
作为初学者,我对 tkinter 不熟悉,也不知道如何改进以下应该像这样运行的代码: 运行 renamer_v.py 文件后,会弹出一个窗口。它在顶部显示一个简短描述,在其下方有一个橙色按钮“单击我”。单击按钮,然后弹出第二个窗口以选择文件夹。文件夹中除隐藏文件和子文件夹外的所有文件标题都将被赋予序列化前缀。
问题是主窗口和第二个窗口同时弹出。但是,后者被设计为在用户单击按钮后出现。
这是我的源代码。 renamer_V1.py:
import win32file
import win32con
import tkinter as tk
from tkinter import Button
from clicked import Clicked
root=tk.Tk()
root.geometry("550x200")
label=tk.Label(root,font=("Arial Bold",15),
text='Please select a directory to rename files in the folder:')
label.pack()
c=Clicked()
btn=Button(root,font=("Arial",15),bg='orange',text="Click Me",command=c.clicked)
btn.pack()
c.clicked()
file_lists=os.listdir(c.file_path)
n=0
for file in file_lists.copy():
oldname=c.file_path+os.sep+file
file_flag=win32file.GetFileAttributesW(oldname)
is_hiden=file_flag & win32con.FILE_ATTRIBUTE_HIDDEN
if os.path.isdir(oldname) or is_hiden:
continue
else:
oldname=c.file_path+os.sep+file
newname=c.file_path+os.sep+'('+str(n+1)+')'+file
os.rename(oldname,newname)
n+=1
label=tk.Label(root,text=str(n)+' file(s) renamed.')
label.pack()
root.mainloop()
clicked.py:
from tkinter import filedialog
class Clicked:
file_path=None
def __init__(self):
print()
def clicked(self):
self.file_path=filedialog.askdirectory(title='ReNamer')
【问题讨论】:
-
是因为你在创建
btn之后调用了c.clicked()。 -
@acw1668: 如果我删除
c.clicked()并再次运行,它会提示:TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' -
您应该将
btn.pack()和label=tk.Label(..)之间的代码块放入一个函数中,然后将此函数分配给btn的command选项。 -
@acw1668 非常感谢。我会试试你的建议。