Appending to clipboard - python-3.x

I feel like I have been asking a lot of questions the last couple days but I really need help with this one. First of its my 3rd day writing code and python is the language of choice that I chose to learn to code.
OK I made this converter that converts units of measurement from mm to inches (and also converts surface finishes) I then want it to copy the converted number (taken out to the third decimal place) to the clipboard so I can paste it in another program. I am trying to do this using tkinter but I keep getting the error message
Traceback (most recent call last):
File "C:\Pygrams\Converter.py", line 104, in <module>
clipboard_append(final_form)
NameError: name 'clipboard_append' is not defined
Here is the code (only posting the part I am having trouble with) im using (assume that variables such as Results are defined elsewhere.
from tkinter import Tk
final_form = ("%.3f" % Results)
final_form2 = str(final_form)
r = Tk()
r.withdraw()
r.clipboard_clear()
clipboard_append(finalform2)
r.destroy()
What am I doing wrong?

You're calling clipboard_append(finalform2) when you should be calling r.clipboard_append(finalform2)

Related

Revit Python Shell / Revit Python Wrapper - get Element name by id

I'm trying to get the name of an element by way the ID using Revit python wrapper in Revit python shell but I'm having issues. I am typically able to do it using c# but rpw is new to me.
I try:
doc.GetElement(2161305).name or doc.GetElement(2161305).Name
and I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected Reference, got int
I've looked a bit through the docs and watched some of the videos but haven't found anything that has covered this. I'm sure its easy, I'm just not not finding the answer.
Any help / direction is appreciated.
Got to answer my own question again.
>>> from rpw import db
>>> element = db.Element(SomeElement)
>>> element = db.Element.from_id(ElementId)
>>> element = db.Element.from_int(Integer) # this one worked for me
You need to cast the integer to an ElementId. The GetElement has three overloads. None of them takes an int, so you need to cast it to clarify which one is intended. Please read the GetElement documentation.

Python script works fine independently, however, when called from an external script, I get NameError name 'x' is not defined

So basically, I am learning Python (therefore I am new, so be gentle lol). I work in IT and wanted to make a program that has all the basic stuff that I do everyday.
The main program opens up and shows a few options for tools and such. I wanted to add a To Do List to the options.
When my To Do list is called the GUI will appear, however, whenever the buttons are clicked, I get the NameError. I assume the main program just doesn't understand the defined functions that I have assigned to the buttons on the To Do list.
I am curious as to why. Of course I would love a solution, however, I am genuinely curious and interested as to why the interpreter doesn't see or "understand" the defined functions.
I called the To Do List using
toDoBtn = tk.Button(self, text = "To Do List",
command=lambda: exec(open("ToDo.py").read()))
The error I get is
Traceback (most recent call last):
File "C:\Users\brannon.harper\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "<string>", line 49, in insertTask
NameError: name 'inputError' is not defined
I will add the beggining part of ToDo.py, however, I feel as if the issue is how I am calling the script, not how the script is written.
from tkinter import *
from tkinter import messagebox
tasks_list = []
counter = 1
# Function for checking input error when
# empty input is given in task field
def inputError() :
if enterTaskField.get() == "" :
messagebox.showerror("Input Error")
return 0
return 1
The ToDo.py script ends with
if __name__ == "__main__" :
# create a GUI window
gui = Tk()
#### I just design the GUI here.
#### After it is designed It ends with
gui.mainloop()
Thanks so much for your time, and this is my first post, so if I did something wrong or didn't follow the "standard entry" please correct me and let me know for the future!
The function inputError isn't defined because exec can't perform any operation that would bind local variables such as importing, assigning variables, or function/class definitions etc.
This is explained more in this SO post, or in the documentation here

Has anyone tried running macro embedded in a microsoft word document from Python

I have a macro in word 2013, that removes white spaces and adjust page width size to ensure the tables fit.
Currently, in order to make these changes to the document, the user needs to run the macro first, and only after running it, when they print the document, the changes are ensured.
I would like to automate the part of running the macro
This is for formating the word doc to ensure that the tables in the document fit the page.
import os
import time
import win32com.client
from docx import Document
macro_to_run = 'PostProcess'
document =
wordapp.Documents.Open('C:\\Users\\sarvesa\\Downloads\\test_xrd.doc')
wordapp.run(document, macro_to_run)
document.save
document.close
Traceback (most recent call last):
File "filename_change.py", line 12, in
wordapp.run(document, macro_to_run)
File "C:\Users\sarvesa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py", line 516, in getattr
ret = self.oleobj.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', "'Run' is not a property.", 'wdmain11.chm', 25342, -2146822426), None)
provided "wordapp" is the instance of word, called like this:
wordapp = win32com.client.DispatchEx("Word.application")
then there are 2 issues:
1) you are missing "Application"
2) These methods are all inherited from VBA, which means you need to use that syntax. This includes casing!
I too had to google a lot of this information and compile it to a working script. I recommend reading some VBA tutorials as well.
Try:
wordapp.Application.Run(macroName)
Edit:
Also your "macro_to_run" might be insufficient.
You need to not only specify the module name, but also the Sub you want to run:
Like "Normal.Module1.SubName"

PyAutoGui.pixelMatchesColor() returns impossible value, with a 10,000 usage limit?

I am creating a program to draw pictures on this site, using PyAutoGui to move the mouse, click, and check some pixel colours on the screen. You can see my testing in the top left hand corner of the canvas. My program relies heavily on the pyautogui.pixelMatchesColor() function, and at certain points my program seemed to break. After trying to find the smallest set of code which would result in the same problem, I got to this:
import pyautogui
no = 0
while True:
if pyautogui.pixelMatchesColor(1750, 180, (255, 255, -1)):
break
num += 1
print(num)
This, as you may have guessed outputted:
10000
The problem here is that once you have used the function more than 10,000 times in one run, it stop working and only returns:
(255, 255, -1)
I have looked around, but can't find anything anywhere on a usage limit of 10,000 for the pyautogui.pixelMatchesColor() function (btw this limit also applies to the pyautogui.pixel() function). It has broken my program, so if you have any information, or a way to circumvent this issue then please let me know. Thank you!
EDIT: After looking into the pyautogui code, it turns out it uses ctypes for mouse controls and PIL for screen utilities. I will try using them instead of pyautogui for more direct code to see if it makes a difference.
For anyone else encountering this bug, I've found a workaround. Instead of calling pyautogui's pixel(x, y) function (which is just a wrapper for ImageGrab's functions), call ImageGrab.grab().getpixel((x, y)) directly. The 10.000 limit is ONLY for the pyautogui.pixel(x, y) function. I don't really know why tho...
from PIL import ImageGrab
pixelRGB = ImageGrab.grab().getpixel((x, y))
Here is a screenshot of my tests with ImageGrab.grab() vs. pyautogui.pixel() (I called ImageGrab.grab() twice as often as pyautogui.pixel())
ImageGrab.grab() fail after about 10k tries of pyautogui.pixel()
And here a screenshot of ONLY ImageGrab.grab().getpixel() calls, I cancelled after x minutes, but it doesn't seem to have a limit.
ImageGrab.grab() without pyautogui.pixel() calls inbetween
Tested on:
Python 3.6.3
Pillow 6.0.0 (PIL)
PyAutoGUI 0.9.42
This might provide insight into this bug. I ran, pyautogui.pixel() until it breaks. I then tried the workaround suggested by viddle...
from PIL import ImageGrab
pixelRGB = ImageGrab.grab().getpixel((100, 125))
Which raised the following exception
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
ImageGrab.grab().getpixel((140,20))
Traceback (most recent call last):
File "", line 1, in
ImageGrab.grab().getpixel((140,20))
File "C:\Users\XisUnknown\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\ImageGrab.py", line 41, in grab
size, data = grabber()
OSError: screen grab failed

Name error when calling defined function in Jupyter

I am following a tutorial over at https://blog.patricktriest.com/analyzing-cryptocurrencies-python/ and I've got a bit stuck. I am tyring to define, then immediately call, a function.
My code is as follows:
def merge_dfs_on_column(dataframes, labels, col):
'''merge a single column of each dataframe on to a new combined dataframe'''
series_dict={}
for index in range(len(dataframes)):
series_dict[labels[index]]=dataframes[index][col]
return pd.DataFrame(series_dict)
# Merge the BTC price dataseries into a single dataframe
btc_usd_datasets= merge_dfs_on_column(list(exchange_data.values()),list(exchange_data.keys()),'Weighted Price')
I can clearly see that I have defined the merge_dfs_on_column fucntion and I think the syntax is correct, however, when I call the function on the last line, I get the following error:
NameError Traceback (most recent call last)
<ipython-input-22-a113142205e3> in <module>()
1 # Merge the BTC price dataseries into a single dataframe
----> 2 btc_usd_datasets= merge_dfs_on_column(list(exchange_data.values()),list(exchange_data.keys()),'Weighted Price')
NameError: name 'merge_dfs_on_column' is not defined
I have Googled for answers and carefully checked the syntax, but I can't see why that function isn't recognised when called.
Your function definition isn't getting executed by the Python interpreter before you call the function.
Double check what is getting executed and when. In Jupyter it's possible to run code out of input-order, which seems to be what you are accidentally doing. (perhaps try 'Run All')
Well, if you're defining yourself,
Then you probably have copy and pasted it directly from somewhere on the web and it might have characters that you are probably not able to see.
Just define that function by typing it and use pass and comment out other code and see if it is working or not.
"run all" does not work.
Shutting down the kernel and restarting does not help either.
If I write:
def whatever(a):
return a*2
whatever("hallo")
in the next cell, this works.
I have also experienced this kind of problem frequently in jupyter notebook
But after replacing %% with %%time the error resolved. I didn't know why?
So,after some browsing i get that this is not jupyter notenook issue,it is ipython issueand here is the issue and also this problem is answered in this stackoverflow question

Resources