Sundararajan Sundararajan - 11 months ago 57
Python Question

OS.rename() not working with tkinter

Folks I'm trying to make a tool which gets user path and file name in one entry and new file name with path in another entry, My aim is to use

os.rename(oldname, newname)
to rename the given file, but its throwing me some error.

My code

from tkinter import *
import os

def Rename_Function(*args):
oldname.set(oldname)#"Renamed Successfully !!! ")

root = Tk()
root.title("MyPython App")

oldname = StringVar()
oldname2= StringVar()
newname= StringVar()
Title1 = Label(root,text="FileName (with path):")
Title1.grid(row=0, column=0)
Oldfilename = Entry(root, textvariable=oldname2)
Oldfilename.grid(row=0, column=1)
Title2 = Label(root, text="New Filename:")
Title2.grid(row=1, column=0)
Newfilename = Entry(root, textvariable=newname)
Newfilename.grid(row=1, column=1)
RenameButton = Button(root, text="RENAME MY FILE", command=Rename_Function)
RenameButton.grid(row=3,columnspan=2, sticky="NWES")
FinalOutput = Label(textvariable=oldname)
FinalOutput.grid(row=4, columnspan=2, sticky = "NWES")

This is how the tool looks

enter image description here

I'm getting the above error when I click the button,
Can someone guide me how to make it work.

I have a doubt that
function should be accessed in some other way since its another module's function. Since I'm learner I don't have any clue how to use them effeciently. Please guide me and explain me so that I would understand this concept better.


To expand upon what @SuperSaiyan said in the comment(s).

You are using a StringVar, which has the method .get() available to it. When you pass the variable which is set to this stringvar you are just passing the reference to this object. You need to actually use the .get() method to get the string.

e.g. - oldname2.get()

Also, for selecting the path you could just use a filedialog, and use os.path.splitext to get the base path + entry in the renaming widget to use as the second parameter with os.rename