Getting the selected extension from Tkinter.asksaveasfilename dialog? - python

I am trying to implement a dialog box in a GUI, and would like to have the selected extension appended to the end of the typed in file name:
and I have come across these following threads:
tkinter: How can I get the users choice of filetype in the asksaveasfilename-dialog?
https://mail.python.org/pipermail/python-list/2002-June/173039.html
Which seems to imply that the asksaveasfilename tool from tkinter does not currently have this function.
Does anyone have a good solution for this? For example something similar to:
filename = asksaveasfilename(
filetypes=[('XLS File', '*.xls'), ('CSV File', '*.csv')],
appendExt=True)
or do I have to write my own just for this little missing function?
Note: This was working perfectly when I ran the code in Ubuntu, but unfortunately not in Windows 10.

Related

pywinauto with a popup window

Im working through pywinauto, not a great developer but I can write some of the basics in python. Im getting hung up though. I have a popup that is causing me to not be able to press ok on and really not sure what direction I need to look
Really a two part question:
How can I move over to this popup IF it occurs, this wont always be the case as sometimes those files may not exist.
I tried using app.Confirm.Ok.click() and also app.Confirm.type('{ENTER}') neither worked.
How can I add in variables that I could call from an external .txt file for things like the "localhost" I included there in my code?
Code here:
from pywinauto import application
import time
app = application.Application()
app.start("Install.exe")
app.SelectLanguage.Ok.click()
app.Platform.Iacceptthetermsinthelicenseagreement.click()
app.Platform.Next.click()
app.Platform.Next.click()
app.PlatformInstallationOptions.Next.click()
app.PlatformSpecifyCertifcate.comboBox.select(0)
app.PlatformSpecifyCertifcate.Next.click()
app.PlatformConfigurationDatabaseOptions.type_keys('{TAB}')
app.PlatformConfigurationDatabaseOptions.type_keys('{TAB}')
app.PlatformConfigurationDatabaseOptions.type_keys('localhost')
app.PlatformConfigurationDatabaseOptions.type_keys('{TAB}')
app.PlatformConfigurationDatabaseOptions.type_keys('{SPACE}')
app.PlatformConfigurationDatabaseOptions.type_keys('{TAB}')
app.PlatformConfigurationDatabaseOptions.type_keys('Config')
app.PlatformConfigurationDatabaseOptions.Next.click()
app.PlatformSpecifyHTTPSBindingCertifcate.type_keys('{TAB}')
app.PlatformSpecifyHTTPSBindingCertifcate.type_keys('{TAB}')
app.PlatformSpecifyHTTPSBindingCertifcate.type_keys('{RIGHT}')
app.PlatformSpecifyHTTPSBindingCertifcate.type_keys('{SPACE}')
app.PlatformSpecifyHTTPSBindingCertifcate.Next.click()
app.PlatformAdvancedWorkflowSettings.Next.click()
app.PlatformPlatformLanguage.Next.click()
app.PlatformInstanceDatabaseOptions.type_keys('{TAB}')
app.PlatformInstanceDatabaseOptions.type_keys('{TAB}')
app.PlatformInstanceDatabaseOptions.type_keys('localhost')
app.PlatformInstanceDatabaseOptions.type_keys('{TAB}')
app.PlatformInstanceDatabaseOptions.type_keys('{SPACE}')
app.PlatformInstanceDatabaseOptions.type_keys('{TAB}')
app.PlatformInstanceDatabaseOptions.type_keys('Instance')
app.PlatformInstanceDatabaseOptions.Next.click()
app.PlatformTimeZone.Next.click()
app.WebApplicationOptions.type_keys('{TAB}')
app.WebApplicationOptions.type_keys('{TAB}')
app.WebApplicationOptions.type_keys('{TAB}')
app.WebApplicationOptions.type_keys('{TAB}')
app.WebApplicationOptions.type_keys('{UP}')
app.WebApplicationOptions.Next.click()
app.WebApplicationOptions.type_keys('{ENTER}')
confirmWin = .app.window(title_re = u'Confirm') #Check your window header object name.
# Use timeout based on average pop up time in your application.
if confirmWin.exists(timeout=10, retry_interval=1):
confirmWin.set_focus()
yesBtn = confirmWin[u'&Yes']
# Check the object name of the Yes button. You can use Swapy tool(It is deprecated but it works, else you can use inspect.exe)
yesBtn.click()
else:
print('Confirmation pop up did not appear')
This should work :)

how to use functions of other .py modules in a GUI (tkinter) module in the same namespace?

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)

Why does asksaveasfilename not return the file type?

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.

Tkinter askopenfilename() won't open

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()

Use file like objects for Tk().iconbitmap()

I am writing a program using Tkinter that is to be eventually compiled into an exe using py2exe. I want to include an icon with it for use on the windows. It will be the same one as I have packed as the icon for the exe. Is there a way to include the icon in Tkinter, either by locating the exe file or using a file-like object? I know that win32api can find the current exe file that's running, but I believe that py2exe extracts the original file to temp, and then runs it, so the original exe couldn't be found that way. I also thought of putting it in an include folder, but I don't know if the cwd would be set correctly for that. Thanks for the help in advance!
Tk images have a -data option which lets you embed the image within the code. You just have to base64-encode the image. I think the image has to originally be in the GIF format.
Here's a working example:
import Tkinter as tk
root = tk.Tk()
data = '''R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9P
T6Ai8P8A/////////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYY
fh8GIEvpoUZcmtOKAO5rLMva0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYw
YtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eTYhJDQ3woDGl7foNiKBV7aYeEkHEi
gnKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOsNYa2q7mcirC5I5Fo
fsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
'''
img = tk.PhotoImage(data=data)
label = tk.Label(image=img)
label.pack()
root.mainloop()
You can embedd the icon in the py2exe binary with the icon_resources option
setup(windows=[
{'script':'toto.py', "icon_resources": [(1, "toto.ico")]},
],
Then you can retrieve it with the windows api
import win32gui, win32api, win32con
from ctypes import c_int, windll
hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 13), True)
and then attach to a window as long as you know his HWND.
windll.user32.SendMessageA(c_int(hwnd), c_int(win32con.WM_SETICON), c_int(win32con.ICON_SMALL), c_int(hicon))
The 13 constant used in the LoadResource has been retrieved with a tool like ResourceHacker. In ResourceHacker, it corresponds to the folder name of the icon. I don't know how it is calculated by py2exe and if there is a way to force this value.
I don't know also if there is a pure TkInter way to do that and if the icon can be used as-is in a tkinter window.
I hope it helps

Categories

Resources