I need some help! This is my code. When i press run it isn't do anything.
I've tried to install again all the modules, but no luck.
from tkinter import *
from tkinter import filedialog
import pyttsx3
from PyPDF2 import PdfFileReader
#Intializing Window
window = Tk('500x350')
window.geometry()
window.config(bg='#6C969D')
window.title("Pdf to Audio Speecch |Nick S")
#Labels
startingpagenumber = Entry(window)
startingpagenumber.place(relx=0.6,rely=0.1)
page1 = Label(window,text="Enter starting page number")
page1.place(relx=0.2,rely=0.1)
label = Label(window, text="Select a book.")
label.place(relx=0.3, rely=0.2)
def file():
path = filedialog.askopenfilename()
book = open(path, 'rb')
pdfreader = PdfFileReader(book)
pages = pdfreader.numPages
speaker = pyttsx3.init()
for i in range(int(startingpagenumber.get()), pages):
page = pdfreader.getPage(i)
txt = page.extractText()
speaker.say(txt)
speaker.runAndWait()
B = Button(window, text="Choose the Book", command=file)
B.place(relx=0.4,rely=0.3)
This is what I get in console
C:\Users\nicks\Desktop\Coding Projects\Python\Pdf to Audio>C:/Users/nicks/AppData/Local/Microsoft/WindowsApps/python3.9.exe "c:/Users/nicks/Desktop/Coding Projects/Python/Pdf to Audio/main.py"
Thanks everyone!
The problem was that I didn't include mainloop() in the end!
Related
My goal is to make a program that lets you edit audio metadata using tkinter, but I've gotten stuck. No matter what I try, the program will not edit the metadata. I am using a browse button so that you can choose any file. Here's my code:
import tkinter
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
import eyed3
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=400, height=300)
audio_file = None
def browse_files():
global audio_file
audio_file_path = askopenfilename(filetypes=(("Audio Files", "*.mp3"),))
audio_file = eyed3.load(audio_file_path)
file_chosen_label = tkinter.Label(root, text=audio_file_path)
file_chosen_label.pack()
return audio_file
def change_artist():
audio_file.tag.album_artist = artist_name.get()
audio_file.tag.save()
return
file_choose_label = tkinter.Label(root, text="Song file")
file_choose = tkinter.Button(root, text="Browse...", command=browse_files)
artist_label = tkinter.Label(root, text="Artist")
artist_name = tkinter.StringVar()
artist_entry = tkinter.Entry(root, textvariable=artist_name)
apply_button = tkinter.Button(root, command=change_artist, text="Apply")
file_choose_label.pack()
file_choose.pack()
artist_label.pack()
artist_entry.pack()
apply_button.pack()
canvas.pack()
root.mainloop()
What am I missing? No errors or anything.
OK, a couple of things:
Change:
def change_artist():
audio_file.tag.genre = artist_name
audio_file.tag.save()
return
To
def change_artist():
audio_file.tag.album_artist = artist_name.get()
audio_file.tag.save()
return
Then, change:
artist_entry = tkinter.Entry(root, textvariable="artist_name")
To:
artist_entry = tkinter.Entry(root, textvariable=artist_name)
Let me know how it goes.
EDIT, I would like to try something. Please change your change_artist function to:
def change_artist():
try:
audio_file.tag.album_artist = artist_name.get()
audio_file.tag.save()
except AttributeError as error:
print(type(audio_file), audio_file)
print(type(audio_file.tag))
raise error
Let me know what get's printed.
EDIT, One more time, try this:
def change_artist():
audio_file.initTag().album_artist = artist_name.get()
audio_file.tag.save()
I have a python code :
import gdal
import numpy
from skimage.filters import threshold_otsu
ds = gdal.Open('A:\\algo\\f2.tif')
In this code, line 4 gives the location/path of "input file" and line 10 gives the location of "output file".
I want to create a user interface to give this location in the user interface itself and run the code from user interface itself.
I have tried making a user interface using "tkinter" module :
from tkinter import *
from tkinter import filedialog
def input():
file1 = filedialog.askopenfile()
label = Label(text=file1).pack()
def input2():
file2 = filedialog.asksaveasfile(mode="w", defaultextension=".tif")
label = Label(text=file2).pack()
w = Tk()
w.geometry("500x500")
w.title("FLOOD_MAPPER")
h = Label(text = "S1A FLOOD MAPPER", bg = "yellow", fg = "black", height = "3", width = "500")
h.pack()
i1 = Label(text = "Input*")
i1.place(x=10, y=70)
i1b = Button(w, text = "Select File", command =input)
i1b.place(x=250, y=70)
i2 = Label(text = "Intermediate Product*")
i2.place(x=10, y=140)
i2b = Button(w, text = "Save as", command =input2)
i2b.place(x=250, y=140)
button = Button(w, text="Generate Map", bg = "red", fg = "black", height = "2", width="30")
button.place(x=150, y=400)
w.mainloop()
But I didn't understand how to link these two codes.
The moment I click on button "generate map" in the user interface I want the location/path of Input and output given in the user interface box to move to their respective places in the 1st code and then run the same code aumoatically.
Kindly, help me to achieve my requirement.
It can look like this. I removed keep only important elements in tkinter.
I put code in your_code and it can get filenames as paramaters. So this code looks similar as before.
I create function gen_map which get run your_code with filenames which are assigned to global variables input_filename, `output_filename.
I assing gen_map to button Button( command=gen_map) so it will run it when you press button.
Other buttons open dialog to get file names and assign to global variables input_filename, output_filename.
from tkinter import *
from tkinter import filedialog
import gdal
import numpy
from skimage.filters import threshold_otsu
def your_code(input_file, output_file):
#ds = gdal.Open('A:\\algo\\f2.tif')
ds = gdal.Open(input_file)
band = ds.GetRasterBand(1)
arr = band.ReadAsArray()
thresh = threshold_otsu(arr,16)
binary = arr > thresh
driver = gdal.GetDriverByName("GTiff")
#outdata = driver.Create("A:\\algo\\test11.tif", 14823, 9985, 1, gdal.GDT_UInt16)
outdata = driver.Create(output_file, 14823, 9985, 1, gdal.GDT_UInt16)
outdata.SetGeoTransform(ds.GetGeoTransform())
outdata.SetProjection(ds.GetProjection())
outdata.GetRasterBand(1).WriteArray(binary)
outdata.GetRasterBand(1).SetNoDataValue(10000)
outdata.FlushCache() ##saves to disk!!
#outdata = None
#band = None
#ds = None
def get_input_filename():
global input_filename
# `askopenfilename` instead of `askopenfile` to get filename instead of object file
input_filename = filedialog.askopenfilename()
input_label['text'] = input_filename
def get_output_filename():
global output_filename
# `asksaveasfilename` instead of `asksaveasfile` to get filename instead of object file
output_filename = filedialog.asksaveasfilename(defaultextension=".tif")
output_label['text'] = output_filename
def gen_map():
#global input_filename
#global output_filename
print('input:', input_filename)
print('output:', output_filename)
your_code(input_filename, output_filename)
#---------------------------------------------
# global variables with default values at start
input_filename = 'A:\\algo\\f2.tif'
output_filename = "A:\\algo\\test11.tif"
root = Tk()
#input_label = Label(root, text=input_filename)
input_label = Label(root, text="Input*")
input_label.pack()
input_button = Button(root, text="Select File", command=get_input_filename)
input_button.pack()
#output_label = Label(root, text=output_filename)
output_label = Label(root, text="Intermediate Product*")
output_label.pack()
output_button = Button(root, text="Save as", command=get_output_filename)
output_button.pack()
gen_map_button = Button(root, text="Generate Map", command=gen_map)
gen_map_button.pack()
root.mainloop()
Hello fellow programmers,
Im trying to make a GUI with Tkinter. This is the first time that Ive used Tkinter, and Ive run into some issues. The script and GUI should do the following:
Ask user (via entry and 'ok' button) to enter the name of the working folder. Result -> Create the newly made folder on the desktop of the system.
Select an OWL file (which is a zip-file) via TkFileDialog.
Result -> unwrap the selected zip-file in the folder that has been created in step 1.
The script Ive written so-far using online tutorials:
import Tkinter
import Tkconstants
import tkFileDialog
import zipfile
from Tkinter import *
import os
class TkFileDialogExample(Tkinter.Frame):
def __init__(self, root):
Tkinter.Frame.__init__(self, root)
root.configure(background='lightgrey')
root.wm_title("Audit tool: Thickness of pavement")
root.geometry('{}x{}'.format(500, 500))
Label_1 = Message(root, text="Step 1. Please fill in the name of the output folder and click on 'create'. The output folder will be created in the desktop folder:", width=380,)
Label_1.grid(row=1, columnspan=5)
Entry1 = Entry(root)
Entry1.grid(row=2, sticky=E)
folder_location = '~/Desktop/' + Entry1.get()
def createname():
return os.mkdir(os.path.expanduser(folder_location))
button_1 = Button(root, text="Create", command=createname)
button_1.grid(row=2, column =1, sticky=W)
Label_3 = Message(root, text="Step 2. Please select the OWL file:", width=300,)
Label_3.grid(row=5, sticky=W)
button_2 = Button(self, text='Click here to select the OWL file', command=self.askopenfilename)
button_2.grid(row=4,column=1, sticky=W)
self.file_opt = options = {}
options['defaultextension'] = '.owl'
options['filetypes'] = [('all files', '.*'), ('owl files', '.owl')]
options['initialdir'] = 'C:\\'
options['initialfile'] = 'Title_of_OWL-file.ccr'
options['parent'] = root
options['title'] = 'This is a title'
self.dir_opt = options = {}
options['initialdir'] = 'C:\\'
options['mustexist'] = False
options['parent'] = root
def askopenfile(self):
return tkFileDialog.askopenfile(mode='r', **self.file_opt)
def askopenfilename(self):
filename = tkFileDialog.askopenfilename(**self.file_opt)
zip_ref = zipfile.ZipFile(filename, 'r')
if filename:
return zip_ref.extractall(folder_location)
if __name__=='__main__':
root = Tkinter.Tk()
TkFileDialogExample(root).grid()
root.mainloop()
The problem probably lies within the third use of 'folder_location'. Since I am relatively new to the Python language, I cannot seem to find a solution to this problem.
Thank you for your help and time!
Yours truly,
Ruben van der Heijden
The issue is that you have defined the variable folder_location only in the local scope of your TkFileDialogExample.__init__ method. As a result, it is not accessible to any of the other methods of your class. If you do want it to be accessible, then you'll want to set it as an attribute of your class using the self keyword.
def __init__(self, root):
# Stuff
self.folder_location = os.path.join('~', 'Desktop', Entry1.get())
Then you can access it from your TkFileDialogExample.askopenfilename method:
def askopenfilename(self):
filename = tkFileDialog.askopenfilename(**self.file_opt)
zip_ref = zipfile.ZipFile(filename, 'r')
if filename:
return zip_ref.extractall(self.folder_location)
Side Note: In general, it is best to use os.path.join to construct file paths from strings.
The program runs only twice. Later, the error occurs. I don't know why it works twice and then stops.
import tkinter, sys, pygame
from tkinter import messagebox
from gtts import gTTS
soundfile="file.mp3"
def ex():
sys.exit()
The main problem is there:
def read():
t = e.get()
tts = gTTS(text=t, lang="en")
tts.save(soundfile)
pygame.mixer.init(frequency=16000, size=-16, channels=2, buffer=4096)
pygame.mixer.music.load(soundfile)
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.play(0,0.0)
while pygame.mixer.music.get_busy()==True:
continue
pygame.quit()
Next is the code for the buttons.
def clear():
e.delete(0, 'end')
main = tkinter.Tk()
e = tkinter.Entry(main, justify = "center")
l = tkinter.Label(main, text = "Write text")
b1 = tkinter.Button(main, text = "Read", command = read)
b2 = tkinter.Button(main, text = "Clear", command = clear)
b3 = tkinter.Button(main, text = "Exit", command = ex)
So, I don't have any idea to fix it.
from gtts import gTTS
import playsound
import os
x = ['sunny', 'sagar', 'akhil']
tts = 'tts'
for i in range(0,3):
tts = gTTS(text= x[i], lang = 'en')
file1 = str("hello" + str(i) + ".mp3")
tts.save(file1)
playsound.playsound(file1,True)
os.remove(file1)
rename the file for every new save, that worked for me.
I currently have this tkintr application that would allow you to upload a file or multiple files. I would like to be able to print to the console how many files were selected.
Currently I can only print what the files selected are with print self.uploadedfilenames
I tried to do len(self.uploadedfilenames) but I got a number of 52 for one file which I do not understand what it is
#!/usr/bin/env python
from Tkinter import *
import tkFileDialog
import tkMessageBox
class Application(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.file_opt = options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
options['initialdir'] = 'C:\\'
options['initialfile'] = 'myfile.txt'
options['parent'] = master
options['title'] = 'This is a title'
#UPLOAD SECTION
Label(frame, text='Upload: ').grid(row=1, column=1)
self.upload = Button(frame, text = "Browse", command = self.askopenfile, width = 10).grid(row=1, column=2)
def askopenfile(self):
self.uploadedfilenames = tkFileDialog.askopenfilenames(multiple=True)
if self.uploadedfilenames == '':
tkMessageBox.showinfo(message="No file was selected")
return
else:
print len(self.uploadedfilenames)
root = Tk()
root.title('application')
_ = Application(root)
root.mainloop()
Is there a way to find out how many files there is ?
The length you see is because it does not return a tuple as expected, but returns a string instead. This is due to a Windows error.
When I test your code on my PC everything is fine.
Please have a look here:
Parsing the results of askopenfilenames()?
Also, when you have issues like this, simply print
self.uploadedfilenames
Then you can see what is returned. That would have helped you out I think.