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.
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 just began python crawling and have tried to crawl web text for a month.
I tried this code with python 2.7.13 and it worked well before.
class IEEECrawler:
def __init__(self):
self.baseUrl = "http://ieeexplore.ieee.org"
self.targetUrl = "http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?reload=true&filter%3DAND%28p_IS_Number%3A4359286%29&rowsPerPage=100&pageNumber=1&resultAction=REFINE&resultAction=ROWS_PER_PAGE&isnumber=4359286#1.html"
self.soup = BeautifulSoup(urllib.urlopen(self.targetUrl).read(), "lxml")
self.doc_list = self.soup.find_all('div', {'class': "txt"})
self.subUrl = []
def crawlOriginalPage(self):
file = open("./result.txt", "w")
for doc in self.doc_list:
head = doc.find("h3")
author_list = ''
for author in doc.find_all("div", {'class':"authors"}):
for tt in author.find_all('span', {'id':"preferredName"}):
author_list += tt['data-author-name'] + ";"
author_list = author_list[:-1]
file.write(head.find("span").text + ';')
file.write(author_list.strip() + ';')
file.write(self.baseUrl+head.find('a')['href']+ ';')
file.write(doc.find("div", {'class': "hide abstract RevealContent"}).find("p").text.replace('View full abstract'+'»'.decode('utf-8'),'').strip()+ '\n')
file.close()
print 'finish'
However, today I ran this code again, I doesn't work with this error masseges. I can't figure out what code should be fixed.
Traceback (most recent call last):
File "/Users/user/Downloads/ieee_fin/ieee.py", line 35, in <module>
crawler.crawlOriginalPage()
File "/Users/user/Downloads/ieee_fin/ieee.py", line 29, in crawlOriginalPage
file.write(doc.find("div", {'class': "hide abstract RevealContent"}).find("p").text.replace('View full abstract'+'»'.decode('utf-8'),'').strip()+ '\n')
AttributeError: 'NoneType' object has no attribute 'find'
The error shows you the line:
file.write(doc.find("div", {'class': "hide abstract RevealContent"}).find("p").text.replace('View full abstract'+'»'.decode('utf-8'),'').strip()+ '\n')
Just look for the method find (there are 2) and check to see what comes before it.
Maybe this is bad:
doc.find(...)
Which would mean that doc was type NoneType, which would mean that doc was None.
Or maybe this is bad:
doc.find("div", {'class': "hide abstract RevealContent"}).find("p")
Which would mean that doc.find(...class...) is returning None. Possibly because it couldn't find any.
Bottom line, you probably either need to put a try...except wrapper around that code, or break it up a little and start checking for None.
This is the error I get:
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensio
ns\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_util.py", line 7
6, in exec_file
exec(code_obj, global_variables)
File "c:\users\tim\documents\visual studio 2013\Projects\Text Game\Text Game\T
ext_Game.py", line 57, in <module>
a_game.play()
File "c:\users\tim\documents\visual studio 2013\Projects\Text Game\Text Game\T
ext_Game.py", line 12, in play
next_scene_name = current_scene.enter() #prints scene's info
AttributeError: 'function' object has no attribute 'enter'
This is my code (written in Python 2.7):
from sys import exit
from random import randint
class Engine(object):
def __init__(self,scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.start_scenes
while True: #this is always running until Death, this pulls next scene up
print "\n--------"
next_scene_name = current_scene.enter() #prints scene's info
current_scene = self.scene_map.next_scene() #this has to take result of scene to play next scene
class Player(object): #once rest of code works we implement more moplicated player traits.
pass
class Scene(object):
def enter(self):
print "Scene info"
exit(1)
class Death(Scene):
quips = [
"Wow. Much Death, so sad. Wow.",
"Hah you suck at this!",
"Try Again!",
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(1)
class Room1(Scene):
def enter(self):
print "Scene Intro"
choice_i = raw_input("\n >")
choice=choice_i.lower()
if choice == "left" or choice == "l":
return "room10"
elif choice == "right" or choice == "r":
return "room2"
else:
print "Choose left or right (l/r)"
return "Room1" #Engine or Map will take the room names to restart a room (or death or finish to end game)
class Map(object):
scenes = {"room1": Room1(), "death": Death()}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def start_scenes(self):
return self.next_scene(self.start_scene)
a_map = Map("Room1")
a_game = Engine(a_map)
a_game.play()
--------
Im a beginner and classes confuse me relatively easily. Im trying to make a text based game (as you porbably noticed its in a lesson from learnpythonthehardway) I want to add a lot of extra functionality past going through rooms but I cant seem to get the rooms working.
Sorry for the info dump but if you could help that would be amazing
.
You forgot to actually call the method.
def play(self):
current_scene = self.scene_map.start_scenes()
...
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.