I am new to Python. I use IDLE (Using python 2.7) on my raspberry pi. I've been unable to compile the latest program from my tutorial, a cat and mouse game. I get the following error:
Traceback (most recent call last) :
File "/home/pi/pyth-prog/Python_Cat_and-mouse.py", line 47, in <module> window.onkeypress(up, "Up")
AttributeError: '__Screen' object has no attribute 'onkeypress'
My code looks like this:
import turtle
import time
boxsize =200
caught= False
score= 0
#function that are called keypresses
def up():
mouse.forward(10)
checkbound()
def left():
mouse.left(45)
def right():
mouse.right(45)
def back():
mouse.back(10)
def quitTurtles():
window.bye()
#stop the ;ouse fro; leaving the square set by box sizes
def checkbound():
global boxsize
if mouse.xcor() > boxsize:
mouse.goto(boxsize, mouse.ycor())
if mouse.xcor() < -boxsize:
mouse.goto(-boxsize, mouse.ycor())
if mouse.ycor() > boxsize:
mouse.goto(mouse.xcor(), boxsize)
if mouse.ycor < -boxsize:
mouse.goto(mouse.xcor(), -boxsize)
#Set up screen
window=turtle.Screen()
mouse=turtle.Turtle()
cat=turtle.Turtle()
mouse.penup()
mouse.penup()
mouse.goto(100, 100)
#add key listeners
window.onkeypress(up, "Up")
window.onkeypress(left, "Left")
window.onkeypress(right, "Right")
window.onkeypress(back, "Down")
window.onkeypress(quitTurtles, "Escape")
difficulty=window.numinput("Difficulty", "Enter a difficulty from easy (1), for hard (5) ", minval=1, maxval=5)
window.listen()
#main loop
#note how it changes with difficulty
while not caught:
cat.setheading(cat.towards(mouse))
cat.forward(8+difficulty)
score=score+1
if cat.distance(mouse) < 5:
caught=True
time.sleep(0.2-(0.01*difficulty))
window.textinput("GAME OVER", "Well done. You scored:"+ str(score*difficulty))
window.bye()
I use IDLE(Using python 2.7) on my raspberry pi
The turtle.py for Python 2.7 only defines onkey() -- the onkeypress() variant was added in Python 3 (as was a synonym for onkey() called onkeyrelease())
Short answer, try changing onkeypress() to onkey().
Once you get past that hurdle, numinput() and textinput() are also Python 3:
difficulty=window.numinput("Difficulty", "Enter a difficulty from easy (1), for hard (5) ", minval=1, maxval=5)
...
window.textinput("GAME OVER", "Well done. You scored:"+ str(score*difficulty))
so they may need to be dealt with too.
Based on turtle from Python 3.5.
It doesn't neeed window. but has to be executed after turtle.Screen()
import turtle
# --- based on turtle in Python 3.5 ---
import tkSimpleDialog
def numinput(title, prompt, default=None, minval=None, maxval=None):
return tkSimpleDialog.askfloat(title, prompt, initialvalue=default,
minvalue=minval, maxvalue=maxval)
def textinput(title, prompt):
return tkSimpleDialog.askstring(title, prompt)
# --- main ---
window = turtle.Screen()
# doesn't need `window.` but has to be executed after `turtle.Screen()`
difficulty = numinput("Difficulty", "Enter a difficulty from easy (1), for hard (5) ", minval=1, maxval=5)
textinput("GAME OVER", "Well done. You scored:" + str(0))
Related
Here is my python code that I am using. I am trying to use a wii remote to trigger a buzzer. I thought this would be an interesting use for my old wii remote. The code that interacts with the buzzer works fine because I used an example script to test it. However, when I try and run it I keep getting this one error (see bottom). I am new to python and would appreciate any help.
import cwiid
from gpiozero import LED
import time
import os
Buzzer1 = LED(17)
Buzzer2 = LED(27)
def ConnectRemote():
os.system("rfkill unblock bluetooth")
print 'Press 1+2 On The Remote...'
global wm
wm = wiid.Wiimote()
print 'Connection Established!\n'
wm.led = 1
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
time.sleep(0.5)
wm.rpt_mode = cwiid.RPT_BTN
def TryToConnect():
while True:
ConnectRemote()
break
while True:
buttons = wm.state['buttons']
#shutdown function using plus and minus buttons
if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
print '\nClosing Connection To Wiimote'
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
os.system("rfkill block bluetooth")
TryToConnect()
if (buttons & cwiid.BTN_A):
print 'Buzzer On'
Buzzer1.on()
Buzzer2.on()
else:
Buzzer1.off()
Buzzer2.off()
and yet I keep getting an error of
Traceback (most recent call last):
File "WiimoteLEDs.py", line 36, in <module>
buttons = wm.state['buttons']
NameError: global name 'wm' is not defined
Can anyone help? Thanks in advance
I think you should initialized variable wm before using this variable in function.
This bug is related to 'Global name not defined'
I am coding for a school project and was trying to use tkinter in my code, but it kept coming up with an error. I am using a mac laptop and the pycharm interface
Traceback (most recent call last):
File "/Users/-----/Desktop/python/Tkinter turtle obstacle.py", line 20, in <module>
color1()#does it automatically
File "/Users/-----/Desktop/python/Tkinter turtle obstacle.py", line 8, in color1
ac1 = Sd("Color Selector", 'Enter the color of the turtle')
TypeError: 'module' object is not callable
Here is my code, its just a simple project to test it before i delve into the final one but I cannot get it to work, can someone please tell me what is wrong with it:
import turtle # 1. import the modules
import random
import Tkinter as tk
import tkSimpleDialog as Sd
def color1():
ac1 = Sd("Color Selector", 'Enter the color of the turtle')
steve.color(ac1)
print(5)
def color2():
ac2 = Sd("Color Selector", 'Enter the color of the obstacle')
sam.color(ac2)
root = tk.Tk()
wn = turtle.Screen() # 2. Create a screen
wn.bgcolor('white')
steve = turtle.Turtle() # 3. Create two turtles
sam = turtle.Turtle()
color1()#does it automatically
color2()
red = tk.Button(root, text = "Enter String", command = color1)#this puts it on a button click
blue = tk.Button(root, text = "Enter String", command = color2)
red.grid(row=0,column=0)
blue.grid(row=1,column=0)
steve.shape('turtle')
sam.shape('circle')
steve.speed(1)
sam.speed(1)
steve.pensize(5)
sam.pensize(25)
sam.penup()
sam.pendown()
steve.penup()
steve.goto(-300,0)
sam.goto(0,0)
b = True
while b is True:
steve.pendown()
steve.forward(20)
if steve.xcor() == sam.xcor() -40:
steve.left(90)
steve.forward(30)
steve.right(90)
if steve.xcor() == sam.xcor() +40:
steve.right(90)
steve.forward(30)
steve.left(90)
if steve.xcor() == 200:
steve.write('Obstacle Avoided', font=('Arial', 20, "bold"))
break
wn.exitonclick()
tkSimpleDialog is a module, not a Class.
You probably want to create an instance of a Class in this module.
Look for the Classes in the module and use the correct Class to create the instance.
I'm was trying this on Linux mint. I have been researching on how to remove packages using the python-apt API. The piece of code below was all I could come up with but nothing happens when I run it. I am trying to remove a single package right now but later I would like to remove a list of packages from a text file. I tried to use the answer found in this post and re-engineered it for removing but my logic does not work. Please give me some input.
#!/usr/bin/env python
# aptuninnstall.py
import apt
import sys
def remove():
pkg_name = "chromium-browser"
cache = apt.cache.Cache()
cache.update()
pkg = cache[pkg_name]
pkg.marked_delete
resolver = apt.cache.ProblemResolver(cache)
for pkg in cache.get_changes():
if pkg.is_installed:
resolver.remove(pkg)
else:
print (pkg_name + " not installed so not removed")
try:
cache.commit()
except Exception, arg:
print >> sys.stderr, "Sorry, package removal failed [{err}]".format(err=str(arg))
remove()
After reading the docs and trying different things, I more or less fixed my problem by coming up with the code below. If someone has a better way, please post. I still want to learn a lot
#!/usr/bin/env python
# aptremove.py
import apt
import apt_pkg
import sys
def remove():
pkg_name = "chromium-browser"
cache = apt.cache.Cache()
cache.open(None)
pkg = cache[pkg_name]
cache.update()
pkg.mark_delete(True, purge=True)
resolver = apt.cache.ProblemResolver(cache)
if pkg.is_installed is False:
print (pkg_name + " not installed so not removed")
else:
for pkg in cache.get_changes():
if pkg.mark_delete:
print pkg_name + " is installed and will be removed"
print " %d package(s) will be removed" % cache.delete_count
resolver.remove(pkg)
try:
cache.commit()
cache.close()
except Exception, arg:
print >> sys.stderr, "Sorry, package removal failed [{err}]".format(err=str(arg))
remove()
In order to get the package list from a file, I took this approach for now.
#!/usr/bin/env python
# aptremove.py
import apt
import apt_pkg
import sys
def remove():
cache = apt.cache.Cache()
cache.open(None)
resolver = apt.cache.ProblemResolver(cache)
with open("apps-to-remove") as input:
for pkg_name in input:
pkg = cache[pkg_name.strip()]
pkg.mark_delete(True, purge=True)
input.close()
cache.update()
if pkg.is_installed is False:
print (pkg_name + " not installed so not removed")
else:
for pkg in cache.get_changes():
if pkg.mark_delete:
print pkg_name + " is installed and will be removed"
print " %d package(s) will be removed" % cache.delete_count
resolver.remove(pkg)
try:
cache.commit()
cache.close()
print "starting"
except Exception, arg:
print >> sys.stderr, "Sorry, package removal failed [{err}]".format(err=str(arg))
remove()
I collected user data using a wx python gui and than I used uno to fill this data into an openoffice document under ubuntu 10.xx
user + my-script ( +empty document ) --> prefilled document
After upgrading to ubuntu 14.04 uno doesn't work with python 2.7 anymore and now we have libreoffice instead of openoffice in ubuntu. when I try to run my python2.7 code, it says:
ImportError: No module named uno
How could I bring it back to work?
what I tried:
installed https://pypi.python.org/pypi/unotools v0.3.3
sudo apt-get install libreoffice-script-provider-python
converted the code to python3 and got uno importable, but wx is not importable in python3 :-/
ImportError: No module named 'wx'
googled and read python3 only works with wx phoenix
so tried to install: http://wxpython.org/Phoenix/snapshot-builds/
but wasn't able to get it to run with python3
is there a way to get the uno bridge to work with py2.7 under ubuntu 14.04?
Or how to get wx to run with py3?
what else could I try?
Create a python macro in LibreOffice that will do the work of inserting the data into LibreOffice and then in your python 2.7 code envoke the macro.
As the macro is running from with LibreOffice it will use python3.
Here is an example of how to envoke a LibreOffice macro from the command line:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
##
# a python script to run a libreoffice python macro externally
# NOTE: for this to run start libreoffice in the following manner
# soffice "--accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" --writer --norestore
# OR
# nohup soffice "--accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" --writer --norestore &
#
import uno
from com.sun.star.connection import NoConnectException
from com.sun.star.uno import RuntimeException
from com.sun.star.uno import Exception
from com.sun.star.lang import IllegalArgumentException
def uno_directmacro(*args):
localContext = uno.getComponentContext()
localsmgr = localContext.ServiceManager
resolver = localsmgr.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
try:
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
except NoConnectException as e:
print ("LibreOffice is not running or not listening on the port given - ("+e.Message+")")
return
msp = ctx.getValueByName("/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory")
sp = msp.createScriptProvider("")
scriptx = sp.getScript('vnd.sun.star.script:directmacro.py$directmacro?language=Python&location=user')
try:
scriptx.invoke((), (), ())
except IllegalArgumentException as e:
print ("The command given is invalid ( "+ e.Message+ ")")
return
except RuntimeException as e:
print("An unknown error occurred: " + e.Message)
return
except Exception as e:
print ("Script error ( "+ e.Message+ ")")
print(e)
return
return(None)
uno_directmacro()
And this is the corresponding macro code within LibreOffice called "directmacro.py" and stored in the User area for libreOffice macros (which would normally be $HOME/.config/libreoffice/4/user/Scripts/python :
#!/usr/bin/python
from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY
from com.sun.star.awt.MessageBoxButtons import DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE
from com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX
def directmacro(*args):
import socket, time
class FontSlant():
from com.sun.star.awt.FontSlant import (NONE, ITALIC,)
#get the doc from the scripting context which is made available to all scripts
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
text = model.Text
tRange = text.End
cursor = desktop.getCurrentComponent().getCurrentController().getViewCursor()
doc = XSCRIPTCONTEXT.getDocument()
parentwindow = doc.CurrentController.Frame.ContainerWindow
# your cannot insert simple text and text into a table with the same method
# so we have to know if we are in a table or not.
# oTable and oCurCell will be null if we are not in a table
oTable = cursor.TextTable
oCurCell = cursor.Cell
insert_text = "This is text inserted into a LibreOffice Document\ndirectly from a macro called externally"
Text_Italic = FontSlant.ITALIC
Text_None = FontSlant.NONE
cursor.CharPosture=Text_Italic
if oCurCell == None: # Are we inserting into a table or not?
text.insertString(cursor, insert_text, 0)
else:
cell = oTable.getCellByName(oCurCell.CellName)
cell.insertString(cursor, insert_text, False)
cursor.CharPosture=Text_None
return None
You will of course need to adapt the code to either accept data as arguments, read it from a file or whatever.
Ideally I would say use python 3, because python 2 is becoming outdated. The switch requires quite a bit of new coding changes, but better sooner than later. So I tried:
sudo pip3 install -U --pre \
-f http://wxpython.org/Phoenix/snapshot-builds/ \
wxPython_Phoenix
However this gave me errors, and I didn't want to spend the next couple of days working through them. Probably the pre-release versions are not ready for prime time yet.
So instead, what I recommend is to switch to AOO for now. See https://stackoverflow.com/a/27980255/5100564 for instructions. AOO does not have all the latest features that LO has, but it is a good solid Office product.
Apparently it is also possible to rebuild LibreOffice with python 2 using this script: https://gist.github.com/hbrunn/6f4a007a6ff7f75c0f8b
I'm trying to use the Python package ComplexNetworkSim, which inherits from networkx and SimPy, to simulate an agent-based model of how messages propagate within networks.
Here is my code:
from ComplexNetworkSim import NetworkSimulation, NetworkAgent, Sim
import networkx as nx
#define constants for our example of states
NO_MESSAGE = 0
MESSAGE = 1
class Message(object):
def __init__(self,topic_pref):
self.relevance = topic_pref
class myAgent(NetworkAgent):
def __init__(self, state, initialiser):
NetworkAgent.__init__(self, state, initialiser)
self.state = MESSAGE
self.topic_pref = 0.5
def Run(self):
while True:
if self.state == MESSAGE:
self.message = self.Message(topic_pref, self, TIMESTEP)
yield Sim.hold, self, NetworkAgent.TIMESTEP_DEFAULT
elif self.state == NO_MESSAGE:
yield Sim.hold, self, NetworkAgent.TIMESTEP_DEFAULT
# Network and initial states of agents
nodes = 30
G = nx.scale_free_graph(nodes)
states = [MESSAGE for n in G.nodes()]
# Simulation constants
MAX_SIMULATION_TIME = 25.0
TRIALS = 2
def main():
directory = 'test' #output directory
# run simulation with parameters
# - complex network structure
# - initial state list
# - agent behaviour class
# - output directory
# - maximum simulation time
# - number of trials
simulation = NetworkSimulation(G,
states,
myAgent,
directory,
MAX_SIMULATION_TIME,
TRIALS)
simulation.runSimulation()
if __name__ == '__main__':
main()
(There may be other problems downstream with this code and it is not fully tested.)
My problem is that the myAgent object is not properly calling the method Run as an attribute. Specifically, this is the error message that I get when I try to run the above code:
Starting simulations...
---Trial 0 ---
set up agents...
Traceback (most recent call last):
File "simmessage.py", line 55, in <module>
main()
File "simmessage.py", line 52, in main
simulation.runSimulation()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/ComplexNetworkSim-0.1.2-py2.7.egg/ComplexNetworkSim/simulation.py", line 71, in runSimulation
self.runTrial(i)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/ComplexNetworkSim-0.1.2-py2.7.egg/ComplexNetworkSim/simulation.py", line 88, in runTrial
self.activate(agent, agent.Run())
AttributeError: 'myAgent' object has no attribute 'Run'
Does anybody know why this is? I can't figure how my code differs substantially from the example in ComplexNetworkSim.
I've run your code on my machine and there the Run method gets called.
My best guess is what Paulo Scardine wrote, but since i can't reproduce the problem i can't actually debug it.