I have a class named TerminalPanel which has the following method:
def OnSerialRead(self, event):
"""Handle input from the serial port."""
text = event.data
Now, I want to get the value of text from another method (get_data) in another class (GraphicsPanel).
How do I get this value? I tried marito = TerminalPanel.OnserialRead.text, but I get AttributeError: 'function' object has no attribute 'text'
Update
I have set-up the TerminalPanel class to include the variable text as part of it:
def OnSerialRead(self, event):
"""Handle input from the serial port."""
self.text = event.data
But now when I call it like this: marito = TerminalPanel.text inside my GraphicsPanel class I get the following error:
AttributeError: type object 'TerminalPanel' has no attribute 'text'
What am I doing wrong?
I think the problem is a lack of context and confusion what actually to do. I suppose you try to rework the wxTerminal.py from pyserial. I have to admit this part of pyserial is neither very readable (has been created by wxGlade) nor is it easy to understand (requires understanding of the wxPython event system and spinning off of threads (to keep the GUI responsive when reading on the serial port).
However, according to your problem description, it seems to me you want to do the following:
Get the value of event.text when it arrives and process it further in your GraphicsPanel instance.
You have to possibilities:
1) Bind to the event:
In your GraphicsPanel class:
class GraphicsPanel(wx.Panel):
def __init__(...):
...
self.parent = self.GetParent() # this should result in a wx.Frame instance!
# binding on wx.Frame required, because wx.Panel will not catch the event
self.parent.Bind(EVT_SERIALRX, self.OnSerialRead)
def OnSerialRead(self, event):
text = event.text
...
event.Skip() # important: you have to skip it also in ``TerminalPanel`` if you
# want to bind twice
2) Call the routine in GraphicsPanel instance with event.text as argument.
class TerminalPanel(wx.Panel):
def __init__(...):
...
self._grphpnl = GraphicsPanel(...)
self.Bind(EVT_SERIALRX, self.OnSerialRead)
def OnSerialRead(self, event):
text = event.text
# do something with it in GraphicsPanel instance
self._grphpnl.OnSerialText(text)
...
Somewhere else in your code:
class GraphicsPanel(wx.Panel):
...
def OnSerialText(text):
# do something with the text
That variable is defined at function scope. There is no way to get that value.
To make the value available to anything outside of the method you need to store the value on the class self.text = event.data or return the value return text
You need to decide what is right for the situation though, I'm guessing by the name of the function that returning the data is the right thing to do.
You need to return the value!
def OnSerialRead(self, event):
"""Handle input from the serial port."""
text = event.data
return text
Then you can access the value like this
marito = TerminalPanel.OnserialRead(event)
Or save the value in the class:
class Reader():
def OnSerialRead(...):
...
self.text = event.data
and then access the value from the class like so:
marito = Reader.text
Related
I struggled to think of a good title so I'll just explain it here. I'm using Python in Maya, which has some event callback options, so you can do something like on save: run function. I have a user interface class, which I'd like it to update when certain events are triggered, which I can do, but I'm looking for a cleaner way of doing it.
Here is a basic example similar to what I have:
class test(object):
def __init__(self, x=0):
self.x = x
def run_this(self):
print self.x
def display(self):
print 'load user interface'
#Here's the main stuff that used to be just 'test().display()'
try:
callbacks = [callback1, callback2, ...]
except NameError:
pass
else:
for i in callbacks:
try:
OpenMaya.MEventMessage.removeCallback(i)
except RuntimeError:
pass
ui = test(5)
callback1 = OpenMaya.MEventMessage.addEventCallback('SomeEvent', ui.run_this)
callback2 = OpenMaya.MEventMessage.addEventCallback('SomeOtherEvent', ui.run_this)
callback3 = ......
ui.display()
The callback persists until Maya is restarted, but you can remove it using removeCallback if you pass it the value that is returned from addEventCallback. The way I have currently is just check if the variable is set before you set it, which is a lot more messy than the previous one line of test().display()
Would there be a way that I can neatly do it in the function? Something where it'd delete the old one if I ran the test class again or something similar?
There are two ways you might want to try this.
You can an have a persistent object which represents your callback manager, and allow it to hook and unhook itself.
import maya.api.OpenMaya as om
import maya.cmds as cmds
om.MEventMessage.getEventNames()
class CallbackHandler(object):
def __init__(self, cb, fn):
self.callback = cb
self.function = fn
self.id = None
def install(self):
if self.id:
print "callback is currently installed"
return False
self.id = om.MEventMessage.addEventCallback(self.callback, self.function)
return True
def uninstall(self):
if self.id:
om.MEventMessage.removeCallback(self.id)
self.id = None
return True
else:
print "callback not currently installed"
return False
def __del__(self):
self.uninstall()
def test_fn(arg):
print "callback fired 2", arg
cb = CallbackHandler('NameChanged', test_fn)
cb.install()
# callback is active
cb.uninstall()
# callback not active
cb.install()
# callback on again
del(cb) # or cb = None
# callback gone again
In this version you'd store the CallbackHandlers you create for as long as you want the callback to persist and then manually uninstall them or let them fall out of scope when you don't need them any more.
Another option would be to create your own object to represent the callbacks and then add or remove any functions you want it to trigger in your own code. This keeps the management entirely on your side instead of relying on the api, which could be good or bad depending on your needs. You'd have an Event() class which was callable (using __call__() and it would have a list of functions to fire then its' __call__() was invoked by Maya. There's an example of the kind of event handler object you'd want here
Inside a custom button class I have a signal which emits when is dropped something into it. Here the relevant method:
class CustomButton
linked = QtCore.pyqtSignal()
...
def dropEvent(self, e):
print e.source().objectName()
print self.objectName()
# set the drop action as LinkAction
e.setDropAction(QtCore.Qt.LinkAction)
# tell the QDrag we accepted it
e.accept()
#Emit linked signal with the drag object's name as parameter
self.linked.emit( e.source().objectName() )
return QtGui.QPushButton.dropEvent(self, QtGui.QDropEvent(QtCore.QPoint(e.pos().x(), e.pos().y()), e.possibleActions(), e.mimeData(), e.buttons(), e.modifiers()))
In otherhand, outside the class, in the main application I'm creating a slot, and a way to connect it to the signal.
#The slot (actually is just a python callable)
def on_link(self):
input = self.sender().objectName()[4:]
print input
#I need to print the name of the other object emitted as str parameter in the signal....
#Instance of custom button
custom_button.linked.connect( lambda: on_link( custom_button ) )
At this point I already know that I can get the sender() of the signal, however, I don't know how to get the parameter of self.linked.emit( e.source().objectName() ). I just know that first I have to change first this: linked = QtCore.pyqtSignal(str), but don't know how to write the connection or the slot and retrieve the e.source().objectName() in the emit signal.
The current design of the slot looks very confusing. At first glance, it looks like an instance method, but it is actually just a module-level function with a fake self parameter.
I would suggest something simpler, and more explicit, like this:
class CustomButton(QtGui.QPushButton):
linked = QtCore.pyqtSignal(str, str)
def dropEvent(self, event):
...
self.linked.emit(self.objectName(), event.source().objectName())
return QtGui.QPushButton.dropEvent(self, event)
def on_link(btn_name, src_name):
print btn_name, src_name
custom_button.linked.connect(on_link)
An alternative design would be to send the objects, instead of their names:
linked = QtCore.pyqtSignal(object, object)
...
self.linked.emit(self, event.source())
def on_link(button, source):
print button.objectName(), source.objectName()
The sample code is like this:
class Something(gtk.Window):
def __init__(self):
...
treeview = gtk.TreeView(store)
tree_selection = treeview.get_selection()
tree_selection.set_mode(gtk.SELECTION_SINGLE)
tree_selection.connect("changed", self.onSelectionChanged)
...
def onSelectionChanged(self, tree_selection):
(model, pathlist) = tree_selection.get_selected()
self.selectedValue = model.get_value(pathlist, 0) - 1
How was the tree_selection passed in into onSelectionChanged function? I see many other similar uses, such as:
def onDestroy(self, widget):
gtk.main_quit()
What can we use this "widget" in the second param?
When you connect a handler (like onSelectionChanged) to a signal (like "changed"), the handler is added to the end of the list of signal handlers of that object.
When the object then emits the signal, it will call handlers (or "callbacks") in this list, pasing itself as the first argument.
This is true for all signals: the first argument is allways the object emitting the signal.
This way, you can e.g. call the get_selected() method of the TreeSelection object that called your onSelectionChanged method: you access it through the tree_selection parameter.
I'm writing a calculator using wxPython for the GUI. I've made a class called display to use StaticText to display the text. Anyways, when I try to update the screen, it raises an exception.
Here's the code:
class display:
def __init__(self,parent, id):
print "display class is working"
global string1
self.view = wx.StaticText(frame, -1, "Waiting", (30,7), style = wx.ALIGN_CENTRE)
#staticmethod
def update(self):
global string1
self.view.SetLabel(string1)
Whenever I try to run the Update() function, it raises this exception:
AttributeError: 'function' object has no attribute 'view'
When I wrote "self.view = wx. etc etc", I tried to set the StaticText to a variable name, so I could use the SetLabel function. The text seems to work until I try to update it. Why can't I update it? How do I fix it?
#staticmethods take no arguments ... so its not actually getting self ... you need to either make it a #classmethod which gets cls or you need to just make it a normal method
class display:
view = None
def __init__(self,parent, id):
print "display class is working"
global string1
display.view = wx.StaticText(frame, -1, "Waiting", (30,7), style = wx.ALIGN_CENTRE)
#classmethod
def update(cls):
global string1
cls.view.SetLabel(string1)
I am updating some code from using libglade to GtkBuilder, which is supposed to be the way of the future.
With gtk.glade, you could call glade_xml.signal_autoconnect(...) repeatedly to connect signals onto objects of different classes corresponding to different windows in the program. However Builder.connect_signals seems to work only once, and (therefore) to give warnings about any handlers that aren't defined in the first class that's passed in.
I realize I can connect them manually but this seems a bit laborious. (Or for that matter I could use some getattr hackery to let it connect them through a proxy to all the objects...)
Is it a bug there's no function to hook up handlers across multiple objects? Or am I missing something?
Someone else has a similar problem http://www.gtkforums.com/about1514.html which I assume means this can't be done.
Here's what I currently have. Feel free to use it, or to suggest something better:
class HandlerFinder(object):
"""Searches for handler implementations across multiple objects.
"""
# See <http://stackoverflow.com/questions/4637792> for why this is
# necessary.
def __init__(self, backing_objects):
self.backing_objects = backing_objects
def __getattr__(self, name):
for o in self.backing_objects:
if hasattr(o, name):
return getattr(o, name)
else:
raise AttributeError("%r not found on any of %r"
% (name, self.backing_objects))
I have been looking for a solution to this for some time and found that it can be done by passing a dict of all the handlers to connect_signals.
The inspect module can extract methods using
inspect.getmembers(instance, predicate=inspect.ismethod
These can then be concatenated into a dictionary using d.update(d3), watching out for duplicate functions such as on_delete.
Example code:
import inspect
...
handlers = {}
for c in [win2, win3, win4, self]: # self is the main window
methods = inspect.getmembers(c, predicate=inspect.ismethod)
handlers.update(methods)
builder.connect_signals(handlers)
This will not pick up alias method names declared using #alias. For an example of how to do that, see the code for Builder.py, at def dict_from_callback_obj.
I'm only a novice but this is what I do, maybe it can inspire;-)
I instantiate the major components from a 'control' and pass the builder object so that the instantiated object can make use of any of the builder objects (mainwindow in example) or add to the builder (aboutDialog example). I also pass a dictionary (dic) where each component adds "signals" to it.
Then the 'connect_signals(dic)' is executed.
Of course I need to do some manual signal connecting when I need to pass user arguments to the callback method, but those are few.
#modules.control.py
class Control:
def __init__(self):
# Load the builder obj
guibuilder = gtk.Builder()
guibuilder.add_from_file("gui/mainwindow.ui")
# Create a dictionnary to store signal from loaded components
dic = {}
# Instanciate the components...
aboutdialog = modules.aboutdialog.AboutDialog(guibuilder, dic)
mainwin = modules.mainwindow.MainWindow(guibuilder, dic, self)
...
guibuilder.connect_signals(dic)
del dic
#modules/aboutdialog.py
class AboutDialog:
def __init__(self, builder, dic):
dic["on_OpenAboutWindow_activate"] = self.on_OpenAboutWindow_activate
self.builder = builder
def on_OpenAboutWindow_activate(self, menu_item):
self.builder.add_from_file("gui/aboutdialog.ui")
self.aboutdialog = self.builder.get_object("aboutdialog")
self.aboutdialog.run()
self.aboutdialog.destroy()
#modules/mainwindow.py
class MainWindow:
def __init__(self, builder, dic, controller):
self.control = controller
# get gui xml and/or signals
dic["on_file_new_activate"] = self.control.newFile
dic["on_file_open_activate"] = self.control.openFile
dic["on_file_save_activate"] = self.control.saveFile
dic["on_file_close_activate"] = self.control.closeFile
...
# get needed gui objects
self.mainWindow = builder.get_object("mainWindow")
...
Edit: alternative to auto attach signals to callbacks:
Untested code
def start_element(name, attrs):
if name == "signal":
if attrs["handler"]:
handler = attrs["handler"]
#Insert code to verify if handler is part of the collection
#we want.
self.handlerList.append(handler)
def extractSignals(uiFile)
import xml.parsers.expat
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = self.start_element
p.ParseFile(uiFile)
self.handlerList = []
extractSignals(uiFile)
for handler in handlerList:
dic[handler] = eval(''. join(["self.", handler, "_cb"]))
builder.connect_signals
({
"on_window_destroy" : gtk.main_quit,
"on_buttonQuit_clicked" : gtk.main_quit
})