Python/Tkinter: Using custom mouse cursors under Windows? - python

Python 2.7/Windows: My understanding is that we can load custom mouse cursors using the cursor='#file.cur' syntax:
widget = tkinter.Label( ..., cursor='#help.cur' )
Here's the traceback I receive:
Traceback (most recent call last):
File "<pyshell#82>", line 1, in <module>
widget.config( cursor='#help.cur' )
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1202, in configure
return self._configure('configure', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1193, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TclError: bad cursor spec "#help.cur"
Is it possible to load custom mouse cursors under Windows using Tkinter, a Tkinter extension, or via a Win32 API call?

lbl=Label(root, text="toto", cursor="#toto.cur") works for me on Python 2.6 and Vista. Make sure that the cur file is in the working directory of your script (I have a similar traceback if I try to load a non-existing cursor) and that the file is not corrupted.
As an alternative, here is a list of internal cursors: http://www.tcl.tk/man/tcl8.4/TkCmd/cursors.htm

Related

Weird error I receive from Tkinter in Python

I am attempting to make a tkinter project but as I tried to run for like the third time it gives me this error:
Traceback (most recent call last):
File "/Users/cool/Documents/STM Wisepay Service.py", line 63, in <module>
app = App(root)
File "/Users/cool/Documents/STM Wisepay Service.py", line 20, in __init__
self.create_buttons()
File "/Users/cool/Documents/STM Wisepay Service.py", line 30, in create_buttons
tk.Button(button_frame, text = "Add to Debt", commmand = self.debt).grid(column = 6, row = 5)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 2366, in __init__
Widget.__init__(self, master, 'button', cnf, kw
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 2296, in __init__
(widgetName, self._w) + extra + self._options(cnf)
_tkinter.TclError: unknown option "-commmand"
What can I do to fix this? What are the problems with my code?
Here is my code:
https://pastebin.com/mWPEFbpz
You are spelling command wrong (three m's)
You are passing it a variable called commmand and it doesn't know how to use that variable.
tk.Button(... commmand = ...
You can see it in the error message right here
_tkinter.TclError: unknown option "-commmand"
These python error messages are actually very helpful. I would encourage you to read them carefully to catch stuff like this.

ImportError: No module named __main__ (Python 2.7 & Pickle)

So on my game I'm making, I'm trying to load the data files needed for the game, and when I load the file with pickle (The file has been loaded, I've double-checked that.) I get this error:
Traceback (most recent call last):
File "/Users/user/Downloads/Deeper-master/Deeper.py", line 257, in <module>
tutorialData = pickle.load(tutorialFile)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1384, in load
return Unpickler(file).load()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 864, in load
dispatch[key](self)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1075, in load_inst
klass = self.find_class(module, name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1130, in find_class
__import__(module)
ImportError: No module named __main__
I saw a question like this on Stack Overflow, but it's a little different than my situation, so sorry if this is a duplicate, I'm just trying to figure it out.
You can find my code here. The main script is Deeper.py, just to save time.
If you notice in your repo, you have a Deeper.pyc and Deeper.py. If I run Deeper.py, it raises the same exception as yours. If I run Deeper.pyc, it raises another exception:
Traceback (most recent call last):
File "Deeper.py", line 7, in <module>
ToolbarTile = pygame.image.load("ToolbarTile.png")
pygame.error: Couldn't open Toolbar Tile.png
So, the code (bytecode, some previous version) references ToolbarTile.png, but the exception is about Toolbar Tile.png (with a space). So I changed the file name to account for that.
Now it raises:
Traceback (most recent call last):
File "Deeper.py", line 766, in <module>
else:
File "Deeper.py", line 394, in __init__
def displayCraft(self):
pygame.error: Couldn't open options.png
There's an Options.png in your files, but it looks for options.png (lower case) (even your new code in Deeper.py looks for that). So I changed that.
Now it works, albeit with Deeper.pyc so that must be why you thought:
(The file has been loaded, I've double-checked that.)
Maybe delete the Deeper.pyc and do a git-bisect to see when the bug was introduced (ps: check your toolbar.dat, does it seem okay to you? Also check the way you're using pickle.load. Maybe you should use rb instead of r?)

Error for Next button in pywinauto using python

I have to currently install windows application, create a new database etc almost everyday when testing the Windows desktop software builds that I get.
To make this job easier, I've decided to use python with pywinauto to automate this process.
Currently I was just trying to write a sample script to automate just another application. Following is my code:
from pywinauto.application import Application
app = Application().start(r"E:\New\any-video-converter.exe -a -n -y -- arguments")
dlg=app['Setup - Any Video Converter Professional']
Now I wanted to click on the 'Next >' button on the setup so I added the following to my code:
app.dlg.Next.Click()
But I get the following error message:
Traceback (most recent call last): File
"C:\Python34\lib\site-packages\pywinauto\application.py", line 243, in
__resolve_control
criteria)
File "C:\Python34\lib\site-packages\pywinauto\timings.py", line 424, in
wait_until_passes
raise err pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in
<module>
app.dlg.NextButton.ClickInput()
File "C:\Python34\lib\site-packages\pywinauto\application.py", line 349, in
__getattribute__
ctrls = self.__resolve_control(self.criteria)
File "C:\Python34\lib\site-packages\pywinauto\application.py", line 246, in
__resolve_control
raise e.original_exception
File "C:\Python34\lib\site-packages\pywinauto\timings.py", line 402, in
wait_until_passes
func_val = func(*args)
File "C:\Python34\lib\site-packages\pywinauto\application.py", line 188, in
__get_ctrl
dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
File "C:\Python34\lib\site-packages\pywinauto\findwindows.py", line
84, in find_element
elements = find_elements(**kwargs)
File "C:\Python34\lib\site-packages\pywinauto\findwindows.py", line 294, in
find_elements
elements = findbestmatch.find_best_control_matches(best_match, wrapped_elems)
File "C:\Python34\lib\site-packages\pywinauto\findbestmatch.py", line 534, in
find_best_control_matches
raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'dlg' in 'dict_keys([])'
Here is the snippet of the UI of the installer: Sample installer UI
I can't understand what's going wrong here. Any help would be appreciated.

what is the best way to start google chrome and input a web address by pywinauto

I learn from blog (http://technapstar.blogspot.fi/2014/07/automation-with-pywinauto.html) about starting google chrome and input a web address by pywinauto as the following way:
Python 3.6.1rc1 (v3.6.1rc1^0:e0fbe5feee4f9c00f09eb9659c2182183036261a, Mar 4 2017, 20:00:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import pywinauto
>>> pywinauto.__version__
'0.6.2'
>>> from pywinauto.application import Application
>>> app = Application().start("chrome.exe")
Warning (from warnings module):
File "D:\Python\lib\site-packages\pywinauto\application.py", line 982
UserWarning)
UserWarning: 32-bit application should be automated using 32-bit Python (you use 64-bit Python)
>>> app.window_(title='New Tab')
<pywinauto.application.WindowSpecification object at 0x0000000002FFABE0>
>>> app.window_().TypeKeys('{F6}')
<pywinauto.controls.hwndwrapper.DialogWrapper object at 0x0000000004258320>
>>> app.window_().TypeKeys('{ESC}')
<pywinauto.controls.hwndwrapper.DialogWrapper object at 0x0000000004243518>
>>> app.window_().TypeKeys('www.google.com')
<pywinauto.controls.hwndwrapper.DialogWrapper object at 0x0000000004225D68>
>>> app.window_().TypeKeys('{ENTER}')
<pywinauto.controls.hwndwrapper.DialogWrapper object at 0x00000000042436D8>
>>>
However, when I try to start another google chrome window with the same way, I meet the following error.
>>> app1 = Application().start("chrome.exe")
Warning (from warnings module):
File "D:\Python\lib\site-packages\pywinauto\application.py", line 982
UserWarning)
UserWarning: 32-bit application should be automated using 32-bit Python (you use 64-bit Python)
>>> app1.window_(title='New Tab')
<pywinauto.application.WindowSpecification object at 0x0000000004243470>
>>> app1.window_().TypeKeys('{F6}')
Traceback (most recent call last):
File "D:\Python\lib\site-packages\pywinauto\application.py", line 243, in __resolve_control
criteria)
File "D:\Python\lib\site-packages\pywinauto\timings.py", line 424, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
app1.window_().TypeKeys('{F6}')
File "D:\Python\lib\site-packages\pywinauto\application.py", line 365, in __getattribute__
ctrls = self.__resolve_control(self.criteria)
File "D:\Python\lib\site-packages\pywinauto\application.py", line 246, in __resolve_control
raise e.original_exception
File "D:\Python\lib\site-packages\pywinauto\timings.py", line 402, in wait_until_passes
func_val = func(*args)
File "D:\Python\lib\site-packages\pywinauto\application.py", line 188, in __get_ctrl
dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
I google a bit, but could not find the answers. Can somebody suggest what is the best way to operate google chrome by pywinauto? or pywinauto is not a proper tool to operate google chrome at the moment.
[EDIT]
Still not working by following Vasily's student sample code, see here:
>>> app = Application(backend='uia');
>>> app.start('chrome.exe --force-renderer-accessibility')
<pywinauto.application.Application object at 0x00000000045D80B8>
>>> app.window().type_keys('{F6}')
<pywinauto.controls.uiawrapper.UIAWrapper object at 0x00000000045D8AC8>
So far it is ok, but when I try to have another chrome browser, I meet following error:
>>> app1 = Application(backend='uia');
>>> app1.start('chrome.exe --force-renderer-accessibility')
<pywinauto.application.Application object at 0x0000000003324F28>
>>> app1.window().type_keys('{F6}')
Traceback (most recent call last):
File "D:\Python\lib\site-packages\pywinauto\application.py", line 243, in __resolve_control
criteria)
File "D:\Python\lib\site-packages\pywinauto\timings.py", line 424, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
app1.window().type_keys('{F6}')
File "D:\Python\lib\site-packages\pywinauto\application.py", line 365, in __getattribute__
ctrls = self.__resolve_control(self.criteria)
File "D:\Python\lib\site-packages\pywinauto\application.py", line 246, in __resolve_control
raise e.original_exception
File "D:\Python\lib\site-packages\pywinauto\timings.py", line 402, in wait_until_passes
func_val = func(*args)
File "D:\Python\lib\site-packages\pywinauto\application.py", line 188, in __get_ctrl
dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
File "D:\Python\lib\site-packages\pywinauto\findwindows.py", line 87, in find_element
raise ElementNotFoundError(kwargs)
pywinauto.findwindows.ElementNotFoundError: {'backend': 'uia', 'process': 2832}
>>>
First you need to run Chrome with accessibility features enabled for all pages (here are some tips and tricks on that):
app = Application().start('chrome.exe --force-renderer-accessibility')
Second Chrome could be easier automated using backend='uia' (MS UI Automation technology) and you need to specify it explicitly. More details about backends and pywinauto fundamentals could be found in the Getting Started Guide (really recommend to read for everyone). It also explains where to find Inspect.exe to browse UI elements hierarchy and much-much more. Just a small example:
app = Application(backend='uia').start('chrome.exe --force-renderer-accessibility')
Third Chrome may start new tabs in different process. So you need to connect to this new process using title or title_re criterion.
app_new_tab = Application(backend='uia').connect(path='chrome.exe', title_re='New Tab')
Alternative way is to use Desktop object (process agnostic way):
NewTab = Desktop(backend='uia').NewTab
NewTab.print_control_identifiers() # prints UI elements subtree
[EDIT] My student wrote an example script dragging zip file from explorer.exe to Google Drive using Chrome in incognito mode: test_explorer_google_drive.py. Tested on English version.
# encoding: utf-8
from __future__ import print_function
from os import path
from pywinauto import Desktop, Application
chrome_dir = r'"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"'
tab_log_in = u'Meet Google Drive - One place for all your files (Incognito)'
tab_drive = 'My Drive - Google Drive (Incognito)'
# # start google chrome
chrome = Application(backend='uia')
chrome.start(chrome_dir + ' --force-renderer-accessibility --incognito --start-maximized '
'https://accounts.google.com/ServiceLogin?service=wise&passive=1209600&continue=https:'
'//drive.google.com/?urp%3Dhttps://www.google.ru/_/chrome/newtab?espv%253D2%2526ie%253DUT%23&followup='
'https://drive.google.com/?urp%3Dhttps://www.google.ru/_/chrome/newtab?espv%253D2%2526ie%253DUT'
'&ltmpl=drive&emr=1#identifier')
# wait while a page is loading
chrome[tab_log_in].child_window(title_re='Reload.*', control_type='Button').wait('visible', timeout=10)
ch_window = chrome[tab_drive].child_window(title="Google Chrome", control_type="Custom")
# log in
chrome.window().type_keys('TestPywinauto{ENTER}') # username
chrome[tab_log_in].child_window(title="Google Chrome", control_type="Custom").\
child_window(title="Back", control_type="Image").wait(wait_for='visible', timeout=10)
chrome.window().type_keys('testpywinauto123{ENTER}') # password
ch_window.child_window(title="Getting started PDF", control_type="ListItem").wait(wait_for='visible')
# start explorer in the current path
dir_path = path.join(path.dirname(path.realpath(__file__)), 'UIA_Drive')
explorer = Application().start('explorer.exe ' + dir_path)
Desktop(backend='uia').window(title='UIA_Drive', active_only=True).wait('visible', timeout=10)
dlg = Application(backend='uia').connect(path='explorer.exe', title='UIA_Drive')
# find file
file = dlg.UIA_Drive.ItemsView.wrapper_object().get_item('test.zip')
# drag n drop
destination = chrome.top_window().wrapper_object()
file.press_mouse_input(coords=file.rectangle().mid_point())
file.move_mouse_input(coords=destination.rectangle().mid_point())
chrome.top_window().set_focus()
file.release_mouse_input(coords=destination.rectangle().mid_point())
# wait upload file
ch_window.child_window(title="test.zip Compressed Archive", control_type="ListItem").wait('visible')
print('DONE')
Simpler way to start is this :
from pywinauto.application import Application
chrome_dir = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
start_args = ' --force-renderer-accessibility --start-maximized https://www.google.com/'
app = Application(backend="uia").start(chrome_dir+start_args)

pandasDataFrame.to_clipboard() error

I have this code to enable CTRL+C copy on the selected contents of a tkinter.ttk treeview:
def Copy(event):
'''
Copies the selected treeview items to the
clipboard. Includes Column numbers.
'''
selectedRows = []
selectedRows.append(self.maindata.columns)
for i in self.tree.selection():
selectedRows.append(self.tree.item(i)['values'])
d = pd.DataFrame(selectedRows)
d.to_clipboard(index=False)
self.tree.bind("<Control-Key-c>", Copy)
This was working fine in plan text.py files executed in IDLE but I'm using the Liclipse IDE for a more confortable debugging experience now and I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "E:\Programming\Anaconda3_4.2.0\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "E:\Programming\EclipseWorkspace\AssetManager\workingTreeview.py", line 90, in Copy
d.to_clipboard(index=False)
File "E:\Programming\Anaconda3_4.2.0\lib\site-packages\pandas\core\generic.py", line 1202, in to_clipboard
clipboard.to_clipboard(self, excel=excel, sep=sep, **kwargs)
File "E:\Programming\Anaconda3_4.2.0\lib\site-packages\pandas\io\clipboard.py", line 98, in to_clipboard
clipboard_set(objstr)
File "E:\Programming\Anaconda3_4.2.0\lib\site-packages\pandas\util\clipboard.py", line 85, in _copyWindows
ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
OSError: exception: access violation writing 0x0000000000000000
Can anyone explain why this is happening and what I need to do to fix it?

Categories

Resources