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()
Related
I am programming a gui using tkinter. I use os.system('file extension'). when I click the button on the gui it should open the next program, but it wont because of python 2. I can use terminal and have pythem3 ./mixed_drink, and this works. Can I set up the code to make the program only run in python 3??
from tkinter import *
import os
##############
root = Tk()
root.title('GET YO DRANK MAIN ')
root.geometry("800x400")
def open_mixed_drinks():
os.system("/home/pi/mixed_drinks.py")
If I understand your question properly, try os.system("python3 /home/pi/mixed_drinks.py")
This way you are passing the .py file to the default installed python3 binary on your system, rather than the global default python which may still be 2.7 on many systems
Tkinter is a great package and filedialog has some very helpful features. Both askopenfilename and asksaveasfilename have the 'filetypes' attribute, but it works differently for each one.
With askopenfilename it provides options in the GUI and returns the filetype, BUT
with asksaveasfilename it only provides options in the GUI and does not return the filetype. Example code is shown below:
import tkinter as tk
from tkinter import filedialog
old_file_name = filedialog.askopenfilename(title = "Choose file",filetypes=\
(('All files','*.*'),\
('tagData','*.tagData'),\
('FDAX files','*.fdax'),\
('CSV files','*.csv')))
new_file_name = filedialog.asksaveasfilename(initialdir = "/",filetypes=\
(('tagData','*.tagData'),\
('FDAX files','*.fdax'),\
('CSV files','*.csv'),\
('XLS files','*.xls')))
print(old_file_name)
print(new_file_name)
Output:
C:/Users/christian.abbott/Desktop/FDAX_Error/example.csv
C:/Users/christian.abbott/Desktop/example
I have looked for good filedialog documentation but have not been able to find it. Why does the package behave this way? Is there a better option to extract the full path of a user-prompted file path?
I had this same problem with Python 3 on Windows 10. I managed to solve it by removing the * before the period in the file types tuples. The following change should, hopefully, do what you want:
new_file_name = filedialog.asksaveasfilename(initialdir = "/",filetypes=\
(('tagData','.tagData'),\
('FDAX files','.fdax'),\
('CSV files','.csv'),\
('XLS files','.xls')))
This worked for me, good luck!
This has nothing to do with tkinter. Windows file explorer hides the file extensions from you by default. So when you see a "example" file in file explorer, Windows is lying to you. The actual filename is "example.csv". Most programs (including python) do not lie, and show you the actual filename.
For entering the filename tkinter uses the OS file selection widget and just displays whatever it returns. I tested it with Win7 and it did not include the extension; however in Debian Jessie it did. If it does not you can always add some code to do it for the user:
if not new_file_name.endswith(('tagData','fdax','csv','xls')):
new_file_name += '.csv'
Search in the start menu for "show extensions" and you can turn this "feature" off.
I'm running a script in a console to help me in a repetitive task.
I want open image in gallery and write down numbers from an image.
feh = subprocess.Popen(['feh', 'tmp.jpg'])
print ("Input number from image:")
number = input()
feh.kill()
This code works, but window managers keep focusing feh, which adds an additional step of refocusing console window. Is there an additional argument I can pass to prevent this behavior or another way around?
One dirty workaround is to simply refocus window by mouse.
I used xdotool
feh = subprocess.Popen(['feh', 'tmp.jpg'])
time.sleep(0.1)
subprocess.call(['xdotool', 'click', '1'])
something = input()
feh.kill()
Python has native GUI modules, named tkinter.
GUI program can be terrifyingly easy to write, if it is python.
#!/usr/bin/python2 -i
from Tkinter import *
from PIL import *
import os
files = [f for f in os.listdir('.') if f.endswith(".png")]
root = Tk()
label = Label(root)
label.pack()
for name in files:
im = PhotoImage(file=name)
label.config(image=im)
print("your number plz")
input_str = raw_input()
To allow my users to choose a file I'm using tkinter's askopenfilename. The function works fine, but after opening a file or pressing cancel the file open window goes empty and just stays open. The rest of the program moves forward correctly but even once the program ends the window remains open. And I'm not getting any errors. Is there anyone else who has experienced this behavior and has a solution? Alternatively, do you know any other easy methods of implementing a GUI file open prompt?
here's a pertinent example:
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
print(filename)
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.