To do some operation with .docx by using python tkinter - python-3.x

I have created a script for getting the path name from user and do some .docx operations. When i run the script it is giving the total number of .docx in that folder but it doesn't work for the table counting. I don't know that I'm using correct code with tkinter. I have tried the pathlib and os.path but it doesn't work.
here is my code:
import os
import glob
import os.path
from docx import Document
from tkinter import *
def print_input():
#To print how many files with .docx extension in the folder
mypath = text_entry.get()
files=0
for name in os.listdir(mypath):
if name.endswith('.docx'):
files=files+1
print("Total No of Files:",files)
#To read the .docx and print how many tables in that
table=0
for name in glob.glob('/*.docx'):
doc=Document(name)
for t in doc.tables:
for ro in t.rows:
if ro.cells[0].text=="ID" :
table=table+1
print("Total Number of Tables: ", table)
root = Tk()
Label(root, text="Enter Path").grid(row=0)
text_entry = Entry(root)
text_entry.grid(row=1, column=0)
text_entry.config(background="yellow", foreground="blue")
Button(root, text='Submit', command=print_input).grid(row=3, column=0, sticky=W, pady=4)
mainloop()
When I try to specify the path name inside the glob it is working but when i try to pass the value from the textbox it is not executing instead of giving correct details it shows random numbers. Hope you understand my problem

Don't have any idea what "doesn't work" means, but you are getting names from "mypath"
for name in os.listdir(mypath):
but tables are coming from '/*.docx'
for name in glob.glob('/*.docx'):
Do it in one operation (and take a look at filedialog.askdirectory)
mypath = text_entry.get()
files=0
for name in os.listdir(mypath):
if name.endswith('.docx'):
files=files+1
#print("Total No of Files:",files)
#To read the .docx and print how many tables in that
table=0
##for name in glob.glob('/*.docx'):
doc=Document(name)
for t in doc.tables:
for ro in t.rows:
if ro.cells[0].text=="ID" :
table=table+1

Related

Error : Continue "Outside of Loop" in python

#Mark the continue statement. I want to bring the control to the beginning of the if-elif condition. so that if user chooses excel after choosing csv , without closing exiting from the window. The label gets updated accordingly on the "root" window. #
# importing tkinter and tkinter.ttk and all their functions and classes
import tkinter
import tkinter.ttk
import os
import sys
import time
# importing askopenfile function from class filedialog
from tkinter.filedialog import askopenfile
root = tkinter.Tk()
root.geometry('400x200')
root.title("CR7 - GSM BSC - Automation Tool ")
label = tkinter.Label(root, text ="Please Select the CR7 Input file for Generating Scripts").pack#(side="top", pady=10)
# This function will be used to open file in read mode and only excel & csv can be opened
def open_file():
file = askopenfile(mode='r', filetypes=[('CSV Files', '*.csv'),('Excel 2003', '*.xls'),('Excel 2007', '*.xlsx')])
filepathstring = str(file)
if filepathstring.find("xls") > 1 or filepathstring.find("xlsx") > 1 and filepathstring.find("csv") <1 :
label1 = tkinter.Label(root, text="Selected file is 'Excel' File & will be converted to 'CSV' file ").pack(side="top",pady=40)
continue
elif filepathstring.find("xls") < 1 or filepathstring.find("xlsx") < 1 and filepathstring.find("csv") > 1 :
label2 = tkinter.Label(root, text="Selected file is 'csv' File ").pack(side="top", pady=20)
continue
btn = tkinter.Button(root, command=lambda: open_file(), text='Open').pack(side="top", pady=10)
root.mainloop()
If I understand you correctly you want to update the first label. Your issue is that you are packing the widgets before creating the reference variable. The python run time environment first creates the widgets; executes the .pack() method; then assigns the variable the results of the .pack() method which is None. Once you have a working reference you can use the .configure() method to change the text value. I didn't run the code, so if there are any issues pleas leave a comment, so I can correct.
# importing tkinter and tkinter.ttk and all their functions and classes
import tkinter
import tkinter.ttk
import os
import sys
import time
# importing askopenfile function from class filedialog
from tkinter.filedialog import askopenfile
root = tkinter.Tk()
root.geometry('400x200')
root.title("CR7 - GSM BSC - Automation Tool ")
label = tkinter.Label(root, text ="Please Select the CR7 Input file for Generating Scripts")
label.pack(side="top", pady=10) # Packing the label before you create a reference creates a reference to the return value of .pack() method which is None
btn = tkinter.Button(root, command=open_file, text='Open') # you don't need to use lambda unless passing a variable
btn.pack(side="top", pady=10)
# This function will be used to open file in read mode and only excel & csv can be opened
def open_file():
file = askopenfile(mode='r', filetypes=[('CSV Files', '*.csv'),('Excel 2003', '*.xls'),('Excel 2007', '*.xlsx')])
filepathstring = str(file)
if filepathstring.find("xls") > 1 or filepathstring.find("xlsx") > 1 and filepathstring.find("csv") <1 :
label.configure(text="Selected file is 'Excel' File & will be converted to 'CSV' file ")
elif filepathstring.find("xls") < 1 or filepathstring.find("xlsx") < 1 and filepathstring.find("csv") > 1 :
label.configure(text="Selected file is 'csv' File ")
root.mainloop()

Tkinter Button with icon: `_tkinter.TclError: image doesn't exist`

In a script, that I am writing I need a button with a little trash bin as an icon on it. I use the code shown below:
# Python 3.7.1
import tkinter as tk
master = tk.Tk()
photo = tk.PhotoImage(file="bin.png")
icon_button = tk.Button(master, image=photo)
icon_button.pack()
The following error occurs:
_tkinter.TclError: image "pyimage1. doesn't exist
Since I specified bin.png as the image file, I cannot really understand how pyimage1 is specified in the error.
After some debugging, I realized, that the PhotoImage returns the string pyimage1, and therefore gives "pyimage1" as a parameter to the Button, but I still don't know how to fix my issue.
The problem is that Relative path won't be accepted, i.e. if you have your bin.png in C:\ then you should do as-
tk.PhotoImage(file='C:\\bin.png')
Now, if you still want to use relative paths then the following will do-
import tkinter as tk
import os
Win = tk.Tk()
Img = tk.PhotoImage(file=os.path.abspath('bin.png')
tk.Button(Win, image=Img).pack()
Win.mainloop()
Or use this-
import sys, os
def get_path(file):
if not hasattr(sys, ''):
file = os.path.join(os.path.dirname(__file__), file)
return file
else:
file = os.path.join(sys.prefix, file)
return file
It simply just gets the full path of a file.
Now, use the function-
...file=get_path('bin.png'))

Defining a list of files using Tkinter to use for analysis. Having a hard time accessing the variables globally. (Python 3)

I hope all is well. Fairly new to programming, so please bear with me.
I am working on a GUI using tkinter that would prompt me to select a set of files that would be used to perform some analysis. I wish to store these files in a list that I can reference later. There are two required files, a DBC file and an ASC file. What I am having issues with is being able to reference the file(s) outside of the functions I have defined. I have tried defining it as a global variable (which I have read is not advisable as it can lead to problems down the road). I get an error saying dbfiles or ascfiles is not defined when just trying to print. Below is what I have written so far:
import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog
root = tk.Tk()
root.geometry("500x700")
def dbbutton():
dbfiles = filedialog.askopenfilenames(parent=root, title='Select .DBC File(s)')
dbfiles = root.tk.splitlist(dbfiles)
for file1 in dbfiles:
L1.insert(tk.END, file1)
return dbfiles
def ascbutton():
ascfiles = filedialog.askopenfilenames(parent=root, title='Select .ASC File(s)')
ascfiles = root.tk.splitlist(ascfiles)
for file2 in ascfiles:
L2.insert(tk.END, file2)
return ascfiles
b1 = tk.Button (root, text= "Select Database File(s)", command = dbbutton)
b1.pack()
L1 = tk.Listbox(root, selectmode = "multiple", height = 10, width = 80)
L1.pack()
b2 = tk.Button (root, text = "Select ASC File(s)", command = ascbutton)
b2.pack()
L2 = tk.Listbox(root, selectmode = "multiple", height = 10, width = 80 )
L2.pack()
root.mainloop()
What is the most effective way for me to reference these files outside of the functions?
Create the file list outside the function and then append to it inside the function:
ascfile_list = [] # Create list to hold filenames
def ascbutton():
filename_list = filedialog.askopenfilenames(parent=root, title='Select .ASC File(s)')
for filename in filename_list:
L2.insert(tk.END, filename)
ascfile_list.append(filename) # Append filename to list

Combining browse method with os.listdir file sorting script

I'm a novice python programmer and i found two pieces of code that combined would basically do what i want from the program i am building. But i have a problem to get them working together. browse_button is a directory browse method that gives me the directory that i would want to do my other method search the sort_button. It would sort files into and if they do not exist it makes the folders. Then it puts the files with specified extensions into those folders.
I have tried to make this work for a few days and i feels stuck. I dont get the second part of the program working with the browse part. Now i get this error when i press the sort button:
"
names = os.listdir(path)
FileNotFoundError: [Errno 2] No such file or directory: ''
"
But i feel dont know why it doesnt have the directory since i can view the directory on the screen before i press the sort button. Can someone explain the problem for me please? <3
""" Filesortingprogramm """
import os
import shutil
from tkinter import filedialog
from tkinter import *
def browse_button():
# Allow user to select a directory and store it in global var
# called folder_path
global folder_path
filename = filedialog.askdirectory()
folder_path.set(filename)
print(filename)
root = Tk()
folder_path = StringVar()
label0 = Label(root, text="Filesorter")
label0.config(font=("Courier", 25))
label0.grid(row=0 ,column=2)
label1 = Label(root, text="open folder to be sorted")
label1.config(font=("Courier", 10))
label1.grid(row=1, column=2)
lbl1 = Label(master=root,textvariable=folder_path)
lbl1.grid(row=2, column=1)
button2 = Button(text="Browse", command=browse_button)
button2.grid(row=3, column=3)
def sort_button()
path = folder_path
path = str()
folder_name = ['text','kalkyl']
names = os.listdir(path)
for x in range(0,2):
if not os.path.exists(path+folder_name[x]):
os.makedirs(path+folder_name[x])
for files in names:
if ".odt" in files and not os.path.exists(path + 'text/' + files):
shutil.move(path+files, path+'text/'+files)
if ".ods" in files and not os.path.exists(path + 'kalkyl/' + files):
shutil.move(path+files, path+'kalkyl/'+files)
button3 = Button(text="Sort", command=sort_button)
button3.grid(row=4, column=3)
mainloop()

Tkinter python 3.5 choose files from file system and assign their path [duplicate]

what I want to do is to select multiple files
using the tkinter filedialog
and then add those items to a list.
After that I want to use the list to process
each file one by one.
#replace.py
import string
def main():
#import tkFileDialog
#import re
#ff = tkFileDialog.askopenfilenames()
#filez = re.findall('{(.*?)}', ff)
import Tkinter,tkFileDialog
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
Now, I am able to select multiple files,
but I dont know how to add those filenames to the list.
any ideas?
askopenfilenames returns a string instead of a list, that problem is still open in the issue tracker, and the best solution so far is to use splitlist:
import Tkinter,tkFileDialog
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root, title='Choose a file')
print root.tk.splitlist(filez)
Python 3 update:
tkFileDialog has been renamed, and now askopenfilenames directly returns a tuple:
import tkinter as tk
import tkinter.filedialog as fd
root = tk.Tk()
filez = fd.askopenfilenames(parent=root, title='Choose a file')
askopenfilenames
returns a tuple of strings, not a string.
Simply store the the output of askopenfilenames into filez (as you've done) and pass it to the python's list method to get a list.
filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
lst = list(filez)
>>> type(lst)
<type 'list'>
Putting together parts from above solution along with few lines to error proof the code for tkinter file selection dialog box (as I also described here).
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
files = filedialog.askopenfilename(multiple=True)
%gui tk
var = root.tk.splitlist(files)
filePaths = []
for f in var:
filePaths.append(f)
filePaths
Returns a list of the paths of the files. Can be stripped to show only the actual file name for further use by using the following code:
fileNames = []
for path in filePaths:
name = path[46:].strip()
name2 = name[:-5].strip()
fileNames.append(name2)
fileNames
where the integers (46) and (-5) can be altered depending on the file path.
In Python 3, the way it worked for me was this (respect lowercase):
from tkinter.filedialog import askopenfilenames
filenames = askopenfilenames(title = "Open 'xls' or 'xlsx' file")
for filename in filenames:
# print or do whatever you want
I hope you find it useful!
Regards!

Resources