I have this little script that counts how many words there are in a file and how many times a word repeats. I want to make a gui in wxPython in which i can enter the filename and it will show me the result.
I've been looking at wxPython examples but still haven't got the hang of it. Here's the script
#!/usr/bin/env python
import sys
import os
import re
import operator
if len(sys.argv) == 1:
sys.exit("Usage: "+sys.argv[0]+" files...");
line = sys.argv[1:]
num = 0
dic = {}
for i in line:
dat = open(i, "r").read()
words = re.findall(r'[a-z]+',dat)
for word in words:
if len(word)>3:
num=num+1
if dic.has_key(word):
dic[word]=dic[word]+1
else:
dic[word]=1
print num
sorted_dic = sorted(dic.iteritems(), key=operator.itemgetter(1), reverse=True)
print sorted_dic
Take a look at wx.FileDialog to get you started. Here's a tutorial that talks about all the standard dialogs, including the file dialog: http://www.blog.pythonlibrary.org/2010/06/26/the-dialogs-of-wxpython-part-1-of-2/ (scroll down about half-way).
Now you'll probably open the file dialog with some sort of button. So you bind the button to EVT_BUTTON and open the file dialog in the event handler. Something like this:
myButton.Bind(wx.EVT_BUTTON, self.openFileDialog)
Now in your openFileDialog (event handler) method, you can open the dialog and retrieve the path. At this point, you pass the path to the code you've already written which can be a part of the event handler or you could put it in its own method. Then when you get the result, you would probably want to display it in a wx.StaticText widget or perhaps show it in a wx.MessageBox
It's not clear what your question is, what part of the GUI (That isn't shown here) are you having trouble with? Instead of wxPython, check out tkinter. In tkinter, you can use the tkFileDialog and get the filepath of the file you want to open and parse, although wxPython has similar funcitonality.
I don't want to write out the code for you, but basically, it'll require:
Create a frame,
Create the button that'll be bound to the command that'll launch the tkFileDialog
Another set of widgets that'll be bound to the command that'll count the words in the file
Display your results somehow.
Related
I am new in tkinter please help me out .
I have implemented a module(PDF2Text.Py) that its class has a function (convert_pdf_to_txt(path)) that takes a path of a pdf file and converts the pdf file into text.
I also implemented another module(TopicModeling.py) that its class has a function (creat_LDA_model(text)) that takes a text and do topic modeling on the text.
Now, I want the tkinter GUI that is, upon clicking the "Browse" button it browses the path with filedialog.askopenfilename and its command function send the given path to convert_pdf_to_txt(path) function of PDF2Text.Py.
Then by clicking the "Model" button, its command function returned text should be sent to creat_LDA_model(text) function in TopicModeling.py and show the result in an Entry widget or any other widget types .
I would like to know the structure of the GUI module;
how to call or get and set the parameters to other modules/functions from the GUI module in command functions of the buttons.
thanks
Seems like you have multiple questions here. I believe one of them is how to start askopenfilename in a particular folder. Once the file name is returned, i can be passed to another function.
fname = askopenfilename(initialdir = r'c:\somepath', filetypes=(("Statement files", "*.pdf"),))
To call other functions you have written, import the module, let's cal it ReadPdf.py, use something like this.
import ReadPdf
PdfOut = ReadPdf.ReadPDFData(fname)
CCStmtTxns = ReadPdf.ReadPDFData(CreditCardPDFDataPathandFile)
So far I'm able to print at the end if the user selects 'n' to not order another hard drive, but need to write to a file. I've tried running the code as 'python hdorders.py >> orders.txt', but it won't prompt for the questions; only shows a blank line and if I break out using Ctrl-C, it writes blank entries and while loops in the file. I hope this makes sense.
ui = raw_input("Would you like to order more hard drives?(y/n) ")
if ui == 'n':
print '\n','\n',"**** Order Summary ****",'\n',row,'\n',"Number of HD's:",b,'\n',"Disk Slot Position(s):",c,'\n',"Disk Size(s):",d,"GB",'\n',"Dimensions:",e,'\n','\n',
endFlag = True
I'd also like it so that if they select 'y', it will save to a file and start over for another disk order (saving the previous info to the file first). Then once they are done (for example going through the program twice) and select 'n', it will have the final details appended to the same file as the first order.
I've found that when extensive user input is desired, a GUI may be the best option. I only try to do command line input if my script uses a small amount of user inputs that I can argparse out. Personally, I would make a tkinter combobox for each of these inputs and have a button at the bottom of the GUI that processes all the inputs and writes them to a file. Here is a skeleton of how I make a GUI
import tkinter as tk
class OOP:
def __init__(self):
self.win = tk.Tk()
self.win.title("My Title")
self.user_input = tk.StringVar()
self.create_widgets()
def lookup_csv_file(self):
file = self.user_input.get()
print(file)
def create_widgets(self):
tk.Button(self.win, text="Lookup CSV file", width=42, command=self.lookup_csv_file).pack(expand=1, fill='both')
tk.Entry(self.win, textvariable=self.user_input).pack(expand=1, fill='both')
app = OOP()
app.win.mainloop()
This code shows several important things to note:
1) GUI's should be made with Object Oriented Programming (OOP) for most cases
2) The variables you want to keep should be initialized in the __init__ section as tk.StringVar(), tk.IntVar(), etc.. and then attached to GUI sections (as seen in create_widgets(self): section the entry's text variable is attached to our varible
3) To access the variable you use its .get() method as seen in lookup_csv_file section. As well the variable has a .set() method if you would like to put a value there. For instance you can do self.user_input = tk.StringVar() followed with self.user_input.set('Default CSV file') and the GUI will initialize with that shown.
4) When assigning commands to buttons, do not include the (). If instead of command=self.lookup_csv_file you put command=self.lookup_csv_file() the command will run during initialization.
These are some of the finer points that were hard for me to learn, but with this you should be able to quickly learn by looking at the documentation available!
I've tried running the code as 'python hdorders.py >> orders.txt', but it won't prompt for the questions
You don't see the prompts since you redirect the standard output, whereto also the prompts go, to the file orders.txt. Better open the file within your program, without redirection at the shell:
if ui == 'n':
orders = open('orders.txt', 'a') # 'a' for appending
print >>orders, '\n','\n',"**** Order Summary ****",'\n',row,'\n',"Number of HDs:",b,…
orders.close()
- run as python hdorders.py.
I have a selection of excel data that I am analyzing, and have just recently added the ability for the user to open the file explorer and locate the file visually, as opposed to entering the file location on the command line. I found this question (and answer) to make the window appear, which worked for a while.
I am still using the command line for everything except locating the file. Currently, this is a skeleton of what I have to open the window (nearly identical to the answer of the question linked above)
Tk().withdraw()
data_file_path = askopenfilename()
# other code with prompts, mostly print statements
Tk().withdraw()
drug_library_path = askopenfilename()
Once the code reaches the first two lines of code, the command line just sits with a blinking cursor, like it's waiting for input (my guess, for askopenfilename() to return a file location), but nothing happens. I can't ctrl+C to get out of the program, either.
I have found this question, which is close to what I'm looking for, but I'm on Windows, not Mac, and I can't even get the window to open -- most questions I see talk about not being able to close the window.
Thanks for any help!
Note: At this point in the program, no data from excel has been loaded. This is one of the first lines that is ran.
Try easygui instead. It's also built on tkinter, but unlike filedialog it's made to run without a full GUI.
Since you are using Windows, use this command in the command line (not in python) to install easygui:
py -m pip install easygui
then try this code:
import easygui
data_file_path = easygui.fileopenbox()
# other code with prompts, mostly print statements
drug_library_path = easygui.fileopenbox()
If you want to use an internal module, you can import tkFileDialog, and call:
filename = tkFileDialog.askopenfilename(title="Open Filename",filetypes=(("TXT Files","*.txt"),("All Files","*.*")))
I use this in many projects, you can add arguments such as initialdir, and you can specify allowable filetypes!
I had the same problem, but I found that the issue was that I was getting input with input() before I called askopenfilename() or fileopenbox().
from tkinter import Tk
from tkinter.filedialog import askopenfilename
var = input()
Tk().withdraw()
filepath = askopenfilename()
I simply switched the positions of askopenfilename() (or fileopenbox()) and input(), and it worked as usual.
Tk().withdraw()
filepath = askopenfilename()
var = input()
I am a newbie in Python and am creating a Tkinter GUI that basically allows users to find desired keywords in .docx files. I have two buttons that both load a pickle file and only one may also add content to the file and save. After using the file under one function(button) and trying to load it up again under the other function(button) the file does not load. It will only load up again after I fully exit the program and run it again. I am not using classes for this program, but I feel that I may have to. I am just not able to bounce between these functions and successfully pass the file. Any advice would be greatly appreciated. Here is the code that may be most useful for this question:
from Tkinter import *
import tkMessageBox
import sys,os,glob,pickle
root = Tk()
root.geometry('400x300')
root.title('Potential Candidate Engine')
Pickle_File = ('Diction.pickle')
if os.path.exists(Pickle_File):
with open(Pickle_File,'r') as rPF:
Dictionary = pickle.load(rPF)
def Clear_Window():
RETURN = sys.executable
os.execl(RETURN, RETURN, * sys.argv)
def SR():
global Dictionary
### Scan the document here ###
def CNP():
global Dictionary
### User adds content here, file saves ###
That 'Clear_Window()' function is just a workaround to return to the main window after the user is done with one function and would like to use the other. It is executed when the RETURN button is pushed
Simple question here: I'd like to use Sikuli to take a screenshot of a window on a mac, which would be done by hitting CMD+SHIFT+4 then hitting Space, then clicking a window.
For the CMD+SHIFT+4 I'm having trouble. This doesn't work:
keyDown(KEY_META)
keyDown(Key.SHIFT)
wait(1)
type("4")
wait(1)
keyUp(Key.SHIFT)
keyUp(KEY_META)
Anyone have any ideas? I'm open to other routes of hitting the key combo, for instance, I know to copy this works well:
type("c",KEY_META)
But, it doesn't accept three arguments.
type("4", KeyModifier.CMD+KeyModifier.SHIFT)
Or, even better:
import shutil
import os
screenshotsDir = "absolute-path-to-a-folder"
img = capture(some_region)
shutil.move(img, os.path.join(screenshotsDir, "some-name.png"))
where some_region is:
some_region = SCREEN # for whole screen
or
someRegion = App.focusedWindow() # for the frontmost window
This has the advantage, that you can control the file name of the shot.
Have found a better solution, which actually works:
screen = Screen()
scr_img = screen.capture(screen.getBounds())
scr_img.save("C:\Screenshots", "screenshot")
Screen.capture() returns an instance of ScreenImage class with methods:'save', 'saveInBundle', 'getFile', 'getFilename'. The method save() adds an unique number to a supplied prefix parameter.