Error message in graphics.py - python

I'm a Highschool Student learning python and I'm a bit stuck on why I am getting an error message in this script. It is supposed to prompt the user for info on how old they are and then return the info in days, hours, and minutes. I'm using the Graphics.py module to accomplish this. The error I am getting is:
how old are you.py", line 17, in <module>
years=entry1.getText()
AttributeError: 'NoneType' object has no attribute 'getText'
I know that the module is properly installed as the getText function works on another script. My code can be seen below. Thanks for any help!
from graphics import*
win=GraphWin('How Old Are You?',250,500)
win.setBackground ('Gray')
entry1= Entry(Point(125,100),10).draw(win)
entry2= Entry(Point(125,200),10).draw(win)
entry3= Entry(Point(125,300),10).draw(win)
Text(Point(125,50),'How many years old are you?').draw(win)
Text(Point(125,150),'What month in the year? (number)').draw(win)
Text(Point(125,250),'How many weeks into the month?').draw(win)
Text(Point(125,25),'When done click outside a box').draw(win)
win.getMouse()
years=entry1.getText()
months=entry2.getText()
days=entry3.getText()
totalDays=(years*365)+(months*30)+(days)
totalHours=((years*365)+(months*30)+(days))*24
totalMinutes=(((years*365)+(months*30)+(days))*24)*60
Text(Point(125,350),totalDays)
Text(Point(125,400),totalHours)
Text(Point(125,450),totalMinutes)

I don't know the graphics library you are using, but your error seems to be trying to accomplish too much at once.
You do:
entry1= Entry(Point(125,100),10).draw(win)
entry2= Entry(Point(125,200),10).draw(win)
entry3= Entry(Point(125,300),10).draw(win)
In each line here, you do create an object - by calling Entry(...), and call a method on that object. The return value of the draw method is what ends up stored in the variables.
Usually, in Python objects, methods won't return their object back. If the method does perform an action (like the name draw ) suggests, it will usually return None - and that is what is happening here, as we see in your error message.
So, all you have to do is to first create your entries, and after that call the draw method on them:
entry1= Entry(Point(125,100),10)
entry2= Entry(Point(125,200),10)
entry3= Entry(Point(125,300),10)
entry1.draw(win)
entry2.draw(win)
entry3.draw(win)
Aside from that, if you don't want your code to be so repetitive, you can create your
entries in a loop and store them in a Python list:
entries = []
for vpos in (100,200,300):
entry = Entry(Point(125,vpos),10)
entries.append(entry)
entry.draw(win)
Text(Point(125,50),'How many years old are you?').draw(win)
Text(Point(125,150),'What month in the year? (number)').draw(win)
Text(Point(125,250),'How many weeks into the month?').draw(win)
Text(Point(125,25),'When done click outside a box').draw(win)
win.getMouse()
years, months, days = (entry.getText() for entry in entries)

Related

return Point(int(firstArg), int(secondArg)) # firstArg and secondArg are just x and y number values

I am trying to have pyautogui move the mouse whenever it detects a color but for some reason whenever I try running it keeps on prompting this error, I have run this code before and it worked perfectly fine. pls help
Code
Output
You are getting that error because "locateAllOnScreen" returns a "generator" which can be looped through which contains all instances of the image. You may be looking for "locateOnScreen".
Here are some example on how to use the two different functions:
# Will loop through all instances of 'img.png'
for pos in pyautogui.locateAllOnScreen('img.png')
# Code here...
# Will find one instance and return the position
pyautogui.locateOnScreen('img.png')
This link has some good information on the different methods

CATIA V5 Automation with Python Script

I'm a Python beginner and am attempting to do some automation in CATIA (Dassault Systemes CAD pacakge) with it, but I've run into an issue that I've been unable to solve despite searching extensively for a solution.
I'm trying to mimic the behavior of this VBA macro that was written within CATIAs native editor interface:
Sub CATMain()
Dim drawingDocument1 As DrawingDocument
Set drawingDocument1 = CATIA.ActiveDocument
Dim selection1 As Selection
Set selection1 = drawingDocument1.Selection
selection1.Search "CATDrwSearch.DrwDimension,all"
For i = 1 To selection1.Count
Dim Dimension1 As DrawingDimension
Set Dimension1 = selection1.Item(i).Value
Dim DimDimValue As DrawingDimValue
Set DimDimValue = Dimension1.GetValue
DimDimValue.SetFormatPrecision 1, 0.001
Next
selection1.Clear
End Sub
To do so I wrote this Python script:
import win32com.client
CATIA = win32com.client.Dispatch('CATIA.Application')
ad = CATIA.ActiveDocument
sel = ad.Selection
sel.Search("CATDrwSearch.DrwDimension,all")
for i in range(1, sel.Count2+1):
aDim = sel.Item2(i).Value
aDimValue = aDim.GetValue
aDimValue.SetFormatPrecision(1,0.001)
sel.Clear
Everything works except for the last operation within the for loop which returns the error:
Traceback (most recent call last):
<bound method DrawingDimension.GetValue of <win32com.gen_py.CATIA V5
DraftingInterfaces Object Library.DrawingDimension instance at 0x67582896>>
File "C:/...", line 15, in <module>
aDimValue.SetFormatPrecision(1,0.001)
AttributeError: 'function' object has no attribute 'SetFormatPrecision'
Note that I used makepy to early bind the COM object otherwise Python doesn't recognize it (returns COMObject [unknown]), but from what I understand that shouldn't impact the script behavior.
I haven't been able to troubleshoot the error successfully because everything I can find suggests the object should have the attribute SetFormatPrecision. I've tried a bunch of other attributes that it should have as well, and none of them work. Because I'm trying to operate on a COM object, I'm not aware of a way to get a comprehensive list of legal attributes, or a way to get any information on the type of object I have stored in aDimValue
I inspected the makepy output file and it does include a function definition for SetFormatPrecision so my guess is I have a syntax issue, but I'm at a loss for what it is.
I know it's a narrowly focused question, but I'm hoping somebody with knowledge of CATIA Object Libraries sees this. And although I don't expect it, if somebody wants to go the extra mile, there's documentation on CATIAs Object Libraries here:
http://catiadoc.free.fr/online/CAAScdBase/CAAScdAutomationHome.htm
Drafting > Drafting Reference > DrawingDimValue
to get to the specific object I think I'm working with in aDimValue
Any help is appreciated. Thanks.
aDim.GetValue returns the function object, rather than calling the function. Use aDim.GetValue(). Same with sel.Clear() on the last line.

Weird error in sklearn.cluster.KMeans

I want to use mr. yasaichi's implementation of x-means written in Python for my master's thesis (yasaichi's x-means: https://gist.github.com/yasaichi/254a060eff56a3b3b858) . For the last few weeks there have been no problem and I have been running the algorithm several times on various data sets. Today, however, a weird error popped up:
AttributeError: 'KMeans' object has no attribute 'get_params'.
The error comes from line 75 in the yasaichi's implementation:
labels = range(0, k_means.get_params()["n_clusters"])
Originally I thought it was me who had done some weird changes to the code, but when I re-downloaded the original again it came up with the same error.
Any ideas?
It sounds like the KMeans object you are trying to use doesn't have the method get_params.
I just tested the code at https://gist.github.com/yasaichi/254a060eff56a3b3b858 and it worked for me. So, my best guess is that you are somehow overwriting the KMeans object or that your code is using a cached version of the code that defines the KMeans object.
To verify this, try adding print dir(k_means) before line 75 of yasaichi's implementation. You should also see that print k_means.__module__ should show sklearn.cluster.k_means_. If this is the case, the final thing I would recommend would be deleting the compiled Python file implementing the k_means_ module. This can be found by running the following:
import sklearn.cluster.k_means_
print sklearn.cluster.__file__

list() gives TypeError: 'Node' object is not callable - BUT ONLY AFTER SOME CODES

I hope this is an easy one for you guys.
This is my script, for Nuke.
selNodes = nuke.selectedNodes()
for list in selNodes:
if list.Class() == 'Read':
layerArray = []
# Get the list of layers and make unique using set
for chanList in list.channels():
channelLayer = chanList.split('.')
layerArray.append(channelLayer[0])
print list(set(layerArray))
It gives an error:
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: 'Node' object is not callable
So I tried a simpler code of the same nature:
a = [1, 1]
print list(set(a))
And it didn't work. Same error message. Now here's the strange thing: I opened up a new Nuke and ran the simpler codes again, it worked. I couldn't understand why, but I was happy. So I put in my original codes and ran it, error message. I deleted them, the editor is now clean. And ran the simpler code again, error message!!
Which means that a working code can be rendered failure after I pasted and deleted something else!
Can anyone shed some light on this issue? Nuke is a very established software I don't know if it's a software bug.
It is because, you are using list as the loop variable, which hides the builtin function list. You are using that function in
print list(set(layerArray))
The loop variables are leaked even when the loop is over, check this program to understand better
for i in range(10):
pass
print(i)
This will print 9. It means that, i is still available in the program even after the loop is over. The case in your program, after iterating over the selNodes, list variable has the last variable. And you are trying to call that like a function when you say
print list(set(layerArray))
That's why it fails. There are two ways to fix this.
Just change the loop variable to something else.
Use del list when the loop is over. Just pretend that I didn't suggest this. This is NOT recommended. Just change the loop variable to something else.

python drag drop init issues

I'm confused as to how I would implement a drag and drop ability for a window and then have the url appear in the textbox.
I've updated where I am stuck at
class controller(NSWindow):
#File to encode or decode
form_file = IBOutlet()
mainWindow = IBOutlet()
#drag and drop ability
def awakeFromNib(self):
self.registerForDraggedTypes_([NSFilenamesPboardType, None])
print 'registerd drag type'
def draggingEntered_(self, sender):
print 'dragging entered doctor who'
pboard = sender.draggingPasteboard()
types = pboard.types()
opType = NSDragOperationNone
if NSFilenamesPboardType in types:
opType = NSDragOperationCopy
return opType
def performDragOperation_(self,sender):
print 'preform drag operation'
pboard = sender.draggingPasteboard()
successful = False
if NSFilenamesPboardType in pboard.types():
print 'my actions finally working'
fileAStr = pboard.propertyListForType_(NSFilenamesPboardType)[0]
print type(fileAStr.encode('utf-8'))
successful = True
print self.form_file
return successful
I can drop the file but I am unable to refrence the form_file outlet from inside of the performDragOperation function. As you can see I am attempting to print it but it returns a NoneType error.
(reason '<type 'exceptions.TypeError'>: 'NoneType' object is not callable') was raised during a dragging session
I believe your problem here was that something earlier in the Responder Chain was handling -[draggingEntered:] and rejecting the drag, before your window could get to it.
For a typical AppKit app, before getting to the window, an action message goes to the First Responder from the NIB, and anything hooked onto the back of it, then the innermost view and its delegate, then all of its ancestor views and their delegates. So if, for example, you have a text edit view that handles drag messages, and you drag over that view, the window won't see it.
Anyway, there are lots of ways to debug this, but the simplest one is to just have each method iterate the nextResponder() chain from self, printing (or logging.logging or NSLogging) the result. Then you can see who you're blocking.
Since there were a bunch of other issues we talked about in the comments, I'm not sure if this was the one that actually solved your problem. But one thing in particular to bring up:
I don't think PyObjC was part of the problem here. When the Cocoa runtime sends an ObjC message like -[draggingEntered:] to a PyObjC object, the PyObjC runtime handles that by looking for a draggingEntered_ method and converting it magically. (Well, I say magic, but it's simple science. Also, because it's sonic, it doesn't do wood.) You need #IBAction in the same places an ObjC program would need (IBAction), which are documented pretty well in the Cocoa documentation.
Meanwhile, one general-purpose debugging tip for PyObjC code (or just about any other event-loop-based or otherwise non-linear code). When you get an error like this:
(reason '<type 'exceptions.TypeError'>: 'NoneType' object is not callable') was raised during a dragging session
It's hard to figure out what exactly went wrong. But you can handle the exception inside the function that raised, and get all the information you want. You can wrap a try/except around each line to figure out which line raised, you can print the whole traceback instead of just the summary, etc.

Categories