I have a problem with python programming, when I'm trying to write a game (introduced by the book: Coding Games Python DK 3), it says:
name 'Actor' is not defined.
here's my code:
import pgzrun
from random import randint
WIDTH = 400
HEIGHT = 400
dots = []
lines = []
next_dot = 0
for dot in range(0, 10):
actor = Actor("dot")
actor.pos = randint(20, WIDTH -20), randint (20, HEIGHT - 20)
dots.append(actor)
def draw():
screen.fill("black")
number = 1
for dot in dots:
screen.draw.text(str(number), (dot.pos[0], dot.pos[1] + 12))
dot.draw()
number = number + 1
for line in lines:
screen.draw.line(line[0], line[1], (100, 0, 0))
pgzrun.go()
You are using the Python library pgzero (indirectly via importing pgzrun).
I had refactored my game code into multiple files (imported into the main file) and did also observe the same strange
NameError: name 'Actor' is not defined
error message.
The Actor class seems to be "private", but can be imported with this simple code line:
from pgzero.builtins import Actor, animate, keyboard
For background see:
https://github.com/lordmauve/pgzero/issues/61
Update Aug 18, 2019: The screen object cannot be imported since it is created as global variable during runtime (object = instance of the Screen class) and IDE-supported code completion is not possible then. See the source code: https://github.com/lordmauve/pgzero/blob/master/pgzero/game.py (esp. the def reinit_screen part)
This page on the Pygame site will help you run it from your IDE: https://pygame-zero.readthedocs.io/en/stable/ide-mode.html
Essentially, you have to have these two lines of code:
import pgzrun
...
...
pgzrun.go()
But during coding, the IDE will still complain that objects and functions like screen and Actor are undefined. Pretty annoying. As far as I know, there's no way to fix it, you just have to ignore the complaints and hit Debug > Run. Provided you have no mistakes, the program will compile and run.
With regards to
import pgzrun
actor = pgzrun.Actor("dot")
Or
from pgzrun import *
dot=Actor("dot")
Neither of these help integrated development environments like Spyder or Visual Studio recognise objects and functions like screen and Actor
pgzrun doesn't seem to behave like a normal python library.
Pygame relies on using pgzrun to run your python script from the command line:
pgzrun mygame.py
In chapter 5, page 73 of Coding Games in Python, step 2 is to save the file as numbers.py. This creates a conflict with the built in module numbers. This is the cause of the error "name 'Actor' is not defined". The solution is to save the file with a different name (i.e. follow.py).
Please define the class Actor or import it from package if you have it in your pip packages or in same dir
From what I could find on the Pygame Documentation website, Actor is defined in the pgzrun package. With your current import statements, you would have to call the Actor constructor by
actor = pgzrun.Actor("dot")
which would show the compiler that Actor belongs to pgzrun.
Alternatively, if you wanted to just use Actor("dot"), you could change your import statement to
from pgzrun import *
which means "import everything from pgzrun". This also keeps track of what comes from pgzrun and tells the compiler, but it could lead to issues (eg. if you define your own Actor constructor in your code, the compiler wouldn't know which one you're trying to use).
well I just found out It has no problem running with cmd, it has problem with running from the software itself.
So, code is correct but I might suspect something. I think you didnt upload a picture called "dot" in pgzero.
I was getting the same error message, until finally I found this topic here. The book version is missing those pgzrun first and last lines.
If you're still getting the error after putting those lines in, I bet your 'python' points to python2. Try this at the command-line:
python -V
If it shows a version of 2, you'll need to fix that. Check
which python
If it's in /usr/bin, you can do:
sudo su
cd /usr/bin
rm python
ln -s python3 python
If it's in an update-alternatives directory, you can run that program to fix it.
I had the exact same problem at the exact same code. After weeks of deleting and rewriting everything that has to do with python on my computer, I realised that it runs if you make the screen. ... lines comments by writing # in the start of each of them. I haven't found how to fix it yet, but I will inform when I will.
I found the issue. Everything on my computer was uploaded automatically to OneDrive. As a result I had a file with the same name on my computer and on OneDrive and when I tried to run it, it always ran from OneDrive where pygame and pgzero are not installed. I solved it by disconnecting auto upload and by changing the name of the file that was on my computer. Hope this works!
the solution is very simple. do not give the file a name.py name because it conflicts with python numbers.py
Related
So I have this simple code below that I am trying to use and I wonder if I am expecting too much from intellisense in VS Code.
I installed the Trello python library using pip3 install py-trello.
Using VS Code (1.27.2), and Python extension (2018.8), Python (3.7.0), Mac OS (10.13.6).
In the code below, if I type board. then I do not see any intellisense help after typing the dot.
I guess it may not be clear to VS Code that board is a class type returned by client.list_boards().
from trello import TrelloClient
client = TrelloClient(
api_key='my_api',
token='my_token',
)
for board in client.list_boards():
print(board.name)
I do get Intellisense popup, if I do this.
x = input("Name: ")
x.
I get a dropdown after x.
However, I do not get intellisense popup with this below sample code either. After I type calc. there is no intellisense popup. Copied this code from another issue on Github but I am using Python 3.7.0. I am facing the same issue, although this issue seems to have been resolved and my application versions are much higher than when the issue was raised and resolved.
class FactorMixin:
Factor_1 = 1
class Calc:
def sum(self, a, b):
return a + b
class BetterCalc(Calc, FactorMixin):
def multiply_factor(self,a):
return a * self.Factor_1
var_a=1
calc = BetterCalc()
calc.
calc.m shows intellisense popup, but calc. does not
And finally, here is one time when the popup does show up. Not sure what is happening and whether it is the language server starting late as some people have experienced in the past...
And when I set "python.jediEnabled": true in settings, the intellisense does pop up, but I wonder what I am losing out on by not using the python server...
Thank you.
I'm using pyautogui to click on a button that periodically pops up on my GUI as shown in the script below. However when the button is not on the screen, the script makes two annoying beep sounds while going through the loop.
If I replace pyautogui.locateOnScreen(...) with None, which seems to be the return value if the image can't be located on the screen, the sound seems to disappear.
The script runs in a Jupyter Notebook (v4) using python 2.7 and I'm on Debian 8.1 with Gnome.
import pyautogui
import time
starttime = time.time()
while time.time()-starttime<10:
img_path_inactive = "/home/user/folder/inactive_target.png"
img_path_active = "/home/user/folder/active_target.png"
img_list = [img_path_inactive, img_path_active]
get_target = map(pyautogui.locateOnScreen, img_list) # <--- This line beeps! See edit 2
if any(get_target):
pyautogui.click(filter(None, get_target)[0][0], filter(None, get_target)[0][1])
# The if check above was previously (hence the title):
# if pyautogui.locateOnScreen(img_path_active) or pyautogui.locateOnScreen(img_path_inactive):
# click_target = pyautogui.locateOnScreen(img_path_active) or pyautogui.locateOnScreen(img_path_inactive)
# pyautogui.click(click_target[0], click_target[1])
time.sleep(2)
print("Finished loop.")
Edit
I put the script in a .py file and ran it from the command line to check if it is a jupyter thing. It still beeped though.
Afterwards I ran pyautogui.locateOnScreen against three images, which caused predictably three beeps... So it definitely seems to be a pyautogui issue/'feature'...
Edit 2
pyautogui.locateOnScreen is imported from here, see line 238. It actually does seem to raise an exception:
except ImageNotFoundException:
if time.time() - start > minSearchTime:
raise
I'm also on GNU/Linux and experiencing beeping when the pyautogui.locateOnScreen() function runs (whether or not it locates the image).
I found that scrot is the culprit. The solution:
$ sudo mv /usr/bin/scrot /usr/bin/scrot-noisy
Create /usr/bin/scrot with these contents:
#!/bin/bash
scrot-noisy --silent "$#"
$ sudo chmod a+x /usr/bin/scrot
Ok, I found a workaround to the beeping.
After going to the source of the module from which pyautogui.locateOnScreen is imported, I believe that the function raises a custom ImageNotFoundException somewhere down the track. I didn't fully debug it though.
Being on Gnome, all Exceptions are announced by an annoying beep.
The workaround that did it for me was to turn off the system beep altogether.
I added the following line to ~/.xsession:
xset b off
which killed the beep.
I have the code below in a file called code.py. I am using IDLE to edit the file. When I click Run>Run Module I get the error:
"IDLE's subprocess didn't make connection. Either IDLE can't start a
subprocess of personal firewall software is blocking the connection."
I am using Windows 7 Ultimate 64bit, but I have the 32bit version of Python 2.7 installed.
I have looked for a solution on this site as well as others but all of them seem to recommend deleting something called tkinter.py (I have no idea what this is) or to turn off my firewalls (I have none enabled aside from Microsoft Security Essentials which isn't a firewall.)
#Globals
#-------------------
x_pad = 476
y_pad = 444
import ImageGrab
import os
import time
import win32api, win32con
def screenGrab():
box = (x_pad+1,y_pad+1,x_pad+641,y_pad+480)
im = ImageGrab.grab(box)
im.save(os.getcwd() + '\\full_snap__' + str(int(time.time())) +
'.png', 'PNG')
def main():
pass
if __name__ == '__main__':
main()
def leftClick():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(.1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
print 'Click.' #completely optional. But nice for debugging purposes.
def leftDown():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(.1)
print 'left Down'
def leftUp():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
time.sleep(.1)
print 'left release'
def mousePos(cord):
win32api.SetCursorPos((x_pad + cord[0], y_pad + cord[1])
def get_cords():
x,y = win32api.GetCursorPos()
x = x - x_pad
y = y - y_pad
print x,y
The thing is "python.exe" is being obstructed by "tkinter.py") that you created(i.e., you have written a program with Tk() and named it as tkinter.py and saved that in the root folder of python). And that's it just make sure that you don't save any program file directly in the root folder of python.
Another fix!!! Hopefully this will help someone.
I had the same problem and noticed something quite interesting. I had accidentally named a file (inside the desktop folder I was working in) "tkinter" (it will cause the same problem if you rename a file by any reserved keyword, I assume). Everytime I ran or attempted to run this file, it created a pycache folder, and the error you mention above came up. Deleting the erroneously named python file solved the problem.
So - look for ANY files (in the folder you are working with or indeed the root folder) that are named after any reserved words. Delete them. Hopefully it'll work!
I had the same problem. what i did that solved it, was to move every .py file that i had created in "C:\Python33" folder, to a sub-folder that i named "Examples". seems like one of my files was the cause of this problem.
I also had the following problem. My file was named code.py, and was working fine untill I installed Canopy, and numpy.
I tried reinstalling python, but what solved the problem for me was simply renaming the file. I called my file myCode.py, everything started working fine. Strange problem...
I made a python file and named it "socket.py" so then python IDLE showing an error on startup that 'startup failure'
so the problem is that if we are using python reserved keywords or module names as our python file name that it conflicts with built-in modules.
the solution is: go to path C:\Users\sony\AppData\Local\Programs\Python\Python38 where your python files are saved and just renamed that file.
then start IDLE.
Happily using IDLE continously under python36 and windows10, it has suddenly given this error on all the programs I'm working on, with no new files created.
I terminated IDLE and tried to restart it with idle.bat but that no longer works.
Happily I have been able to restart it successfully with Lib\idlelib\idle.pyw.
All my recent programs are there and they can again be run without problems.
No need to reinstall python.
I apologize in advance if there is somewhere the same thread of mine.
I am new in Python programming and trying to compute an example from "Programming Computer Vision with Python" written by Jan Erik Solem.
Here is the code of the example (saved in a file called "harris.py"):
https://github.com/jesolem/PCV/blob/master/pcv_book/harris.py
(Be aware that my code ends at line 70)
After a good explanation of this code, in the book is stated: "Try running the following commands:"
im = array(Image.open(’empire.jpg’).convert(’L’))
harrisim = harris.compute_harris_response(im)
filtered_coords = harris.get_harris_points(harrisim,6)
harris.plot_harris_points(im, filtered_coords)
The problems I've encountered are two:
I am not sure where to run those last lines of code, in harris.py
or in a separate python file.
In whichever file I run it, the following error is shown:
harrisim = harris.compute_harris_response(im)
NameError: name 'harris' is not defined
I don't understand why this error is shown, since 'harris' should call the python script harris.py. Or am I wrong?
It is meant to go into a separate file, but you need to import the harris module first:
import harris
before the module is available to your code.
Harris name does not exists in your script (it was not initialised at any time before using it, so Python does not know what harris is). If import harris does not work, it is because the fact that you do not have any module called that way.
I have recently got into learning python, and when I close the IDLE and save my work.
When I come back to it open idle and open my saved work and go to test it with f5 run module, module doesnt produce and error codes and doesnt even print out my simple print commands. how ever if i type up a new project quickly with a few commands it works fine its just my previously saved work...
anyone have any ideas ?
my OS is windows 7 home and it may help to know I have previously installed 3.2 and 2.6
EDIT: turns out my code won't run in command through python either my code seems to be fine but will post it here:
import random
import time
Coin = 100
Health = 100
PCName = ()
def displayIntro():
print "You wake, bound to the cell wall by shackles..."
exectuting this module won't do anything. You just make some imports, define some globals, and define a function. If you want to see something printed, you must call your function:
import random
import time
Coin = 100
Health = 100
PCName = ()
def displayIntro():
print "You wake, bound to the cell wall by shackles..."
displayIntro() # when the interpreter reaches this line, a warm welcome will be printed
That code you wrote is Python 2, not 3. Here is how you should call print():
print("You wake, bound to the cell wall by shackles...")