【问题标题】:Selecting directory by browse button通过浏览按钮选择目录
【发布时间】:2020-12-08 23:56:58
【问题描述】:

我正在开发一个简单的重命名程序,但我面临两个问题:

  1. 如果我为“浏览”添加一个新按钮来选择一个文件夹,我会遇到一些错误。

  2. 如果我运行程序,文件夹选择窗口会自动显示,但我希望每次单击按钮时都运行它。

问题是我可以做一个按钮,它也可以浏览和选择文件夹 但我怎样才能将它绑定到我的工作路径而不会出错?我想有一些问题

list = os.listdir(path) 
os.chdir(path)

完整代码是:

import os
from tkinter import *
#from PIL import ImageTk,Image
from tkinter import filedialog

window = Tk()
window.title("Rename Helper")
window.geometry("500x302")
window.resizable(width = False , height = False)
#window.iconbitmap('licon.ico')

#canvas = Canvas(window)
#image = ImageTk.PhotoImage(Image.open('Rename.png'))
#canvas.create_image(0, 0, anchor=NW, image=image)
#canvas.place( height=500, width=500)

hl_text = StringVar()
e1 = Entry(window, textvariable=hl_text)
e1.place(height=22, width=100, x= 280, y=140)

d_text = StringVar()
e2 = Entry(window, textvariable=d_text)
e2.place(height=22, width=100, x= 280, y=192)

fileExt = (".png", ".jpg", ".jpeg", ".PNG", "JPG", ".JPEG")
def rename(path, new_name, numbering, d_text, extension,):
    list = os.listdir(path)
    os.chdir(path)
    count = numbering
    for i in list:
        if i.endswith(fileExt):
            os.rename(i, new_name + "_P_" + str(count).zfill(2) + "_" + d_text + '.' + extension)
            count += 1

path = filedialog.askdirectory()

def renamebtn():
    newname = hl_text.get()
    newdate = d_text.get()
    rename(path, newname, 1, newdate, "jpg")

btn1 = Button(window, text="Rename", command=renamebtn)
btn1.place(height=50, width=200, x= 280, y=235)

window.mainloop()

【问题讨论】:

  • 也要包含错误代码
  • 您发布的代码不包含“浏览”按钮。

标签: python python-3.x directory path


【解决方案1】:

它自动运行的原因是因为您调用了函数(使用()),要解决这个问题,只需像使用普通函数一样分配一个按钮并将路径放入其中。喜欢:

btn2 = Button(window,text='Choose',command=choose)
btn2.pack() # or even place, depending on what you used previously

那么函数应该是这样的:

def choose():
    global path
    path = filedialog.askdirectory()

这将使filedialog仅在您单击按钮时弹出。

如果有任何疑问或错误,请告诉我

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 2019-08-27
    • 2013-04-25
    相关资源
    最近更新 更多