tkSimpleDialog pycharm - python-2.7

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.

Related

Wolframalpha in python with GTTS

I am trying to make a Friday like virtual assistant using this code
import os
from gtts import gTTS
import time
import playsound
import speech_recognition as sr
while True:
def speak(text):
tts = gTTS(text=text, lang="en")
filename = "voice.mp3"
tts.save(filename)
playsound.playsound(filename)
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said
text = get_audio()
if "who are you" in text:
speak(" I am Monday the virtual assistant")
And i was wondering how to put wolfram alpha in it so i would, say search for ..., then it would speak the answer from wolfram alpha.
Any help would be amazing :)
Install wolframalpha
Then add the following to your code:
import wolframalpha
if 'search for ' in text:
text = text.replace("search for ", "")
client = wolframalpha.Client(app_id)
res = client.query(text)
print(next(res.results).text)
speak(next(res.results).text)
To use the API, you have to go to the homepage, sign up for an account, create an app and get an app id.
To avoid getting any errors, keep the indentation in your 'speak' function uniform.

Error ALDialog Python Nao

I have a problem when using the ALDialog module on Python IDE and to load on Nao. I tried in different ways to load a dialogue but I always fall back on the same error.Runtimeerror LoadTopic::ALDialogIncorrect file myDialog.topIn the first case I write directly the text that I save in a. top file but at the time of LoadTopic () I have an error.In the second case I want to load the. top file by giving it the path. I come back to the same mistake again.Do you have a solution to my problem?Thank you very much.
import qi
import argparse
import os
import sys
from naoqi import ALProxy
def main(robot_ip, robot_port):
dialog = """
topic: ~myTopic() \n
language: enu \n
u:(test) hello \n """
file = open("myDialog.top","w")
file.write(dialog)
file.close()
# load topic
proxy = ALProxy("ALDialog",robot_ip,robot_port)
proxy.setLanguage("English")
self.topic = proxy.loadTopic("myDialog.top")
# start dialog
proxy.subscribe("myModule")
# activate dialog
proxy.activateTopic(self.topic)
if name == "main":
parser = argparse.ArgumentParser()
parser.add_argument("--ip", type=str,
default="169.254.245.164",help="Robot's IP address : '169.254.245.164'")
parser.add_argument("--port", type=int, default=9559,help="port number, the default value is OK in most cases")
args = parser.parse_args()
main(args.ip, args.port)
ALDialog.loadTopic expects an absolute filepath on the robot - it doesn't know anything about the context from which you're calling it (it could be from another computer, in which case of course it can't open that file). You need to be sure that your .top is indeed on the robot, and pass it's absolute path to ALDialog.
Once installed on the robot this path will be something like /home/nao/.local/share/PackageManager/apps/your-package-id/your-dialog-name/your-dialog-name_enu.top

Python attribute error onkeypress

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))

PyQt - Getting an error when trying to use emit

I am trying to use emit for the first time in PyQt. I have done a lot of reading and googling and I was sure I had this correct but I keep getting the errors shown below. Can anyone shed some light on what I am doing wrong.
def checkRiskDescription(obj,form):
complete = True
if str(form.txtTitle.text()) == "":
complete = False
if len(str(form.txtOverview.toPlainText())) < 50:
complete = False
bar = form.tabRiskMain.tabBar()
if complete:
#Change Risk Description tab to Green
bar.setTabTextColor(0,QtGui.QColor(38, 169, 11, 255))
form.btnSave.enabeld = True
else:
#Change risk Description tab to Red
bar.setTabTextColor(0,QtGui.QColor(255, 0, 0, 255))
form.btnSave.enabled = False
QtGui.QWidget.emit(QtCore.SIGNAL("tabsUpdated"))
Here is the error
File "D:\Development\python\PIF2\PIF\risk\risk.py", line 360, in checkRiskDescription
QtGui.QWidget.emit(QtCore.SIGNAL("tabsUpdated"))
TypeError: QObject.emit(SIGNAL(), ...): first argument of unbound method must have type 'QObject'
I normally just define the signal like this
tabsUpdated = Qt.pyqtSignal()
then fire it via
self.tabsUpdated.emit()
E.g
from PyQt4 import Qt
class SomeClass(Qt.QObject):
tabsUpdated = Qt.pyqtSignal()
def __init__(self):
Qt.QObject.__init__(self)
def something(self):
# bla bla loads of nice magic code bla bla
self.tabsUpdated.emit()
of course the signal could be defined globally in your python file.

Why can't an object use a method as an attribute in the Python package ComplexNetworkSim?

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.