http://tinypic.com/r/5dv7kj/7
How can i show the message like in the picture(top right)?
I'm new to linux and now tring to use pygtk to make a client application to show/popup some random hint/mems.
Using traditional winodw is OK,but this one is much more friendly to me.I have tried scanning through the pygtk guide but still missing the solution.Other
Is there any body could give me some hint?Any python GUI libs are also OK.
It's an Ubuntu specific thing called NotifyOSD. There are examples of programming for it here.
Quick and Dirty codes in python
import pynotify
# Only Text Notification
pynotify.init('Basic')
pynotify.Notification("Title", "simple text").show()
# Lets try with an image
pynotify.init('Image')
## Use absolute Path of the photo
pynotify.Notification("Title", "My Photo here!!", "/home/nafis/Pictures/me.png").show()
# Try Markup
pynotify.init("markup") ## all smallerCase "markup"
# but in parameter, first letter capital
pynotify.Notification("Markup",
'''
<b>bold</b>, <i>italic</i>, <u>underline</u>
and even links are supported!
'''
).show()
Also You can use it from shell (I use lubuntu, it works here.)
#!/bin/bash
### try it in terminal
notify-send -t 900 "Title" "Message"
A simple method without any additional packages.
you can execute commands via os.system.
import os
def message(title, message):
os.system(f"notify-send '{title}' '{message}'")
message("Title", "Im message")
Related
I am trying to change the keyboard language in python (windows). I have searched everywhere for a way to do it and the most common answer is
import win32api
win32api.LoadKeyboardLayout('00000409',1) # to switch to english
win32api.LoadKeyboardLayout('00000401',1) # to switch to arabic
But the only thing this code does is add another language to the current list of languages on my pc - it doesn't change the language's keyboard (when I try typing something after I ran the script it keeps typing in the same language).
BTW, I am using windows
Thank you in advance for any help!
שלום נגה.
I managed to do it with keyboard events & shortcut assignment.
go to windows 7 > control panel > "text services and input language" (or right-click langauge-bar > settings)
assign keys for the uni-directional language. e.g. "To English", and "To Hebrew". I've chosen Alt-Shift-7 and Alt-Shift-8, because they're rarely used elsewhere.
from your app, send the key combination for the appropriate language, when needed.
Note:
if "your app" is an external utility (I wrote mine in Python), then it must NOT invoke a window, otherwise /your-app/ will steal the focus, and will get the language change. in python I solved it by using a GUI-less pyw script filename. (or invoke the script with pythonw.exe)
this article shows how to send keyboard events in python:
https://python-decompiler.com/article/2012-11/how-to-generate-keyboard-events-in-python
This is works for me
from win32con import WM_INPUTLANGCHANGEREQUEST
from win32gui import GetForegroundWindow
from win32api import SendMessage
if SendMessage( GetForegroundWindow(), WM_INPUTLANGCHANGEREQUEST, 0, 0x4090409) == 0:
print('設定英文鍵盤成功!')
I am making an app in python 2.7 on mac osx 10.8.5 I want to show notification number of times, therefore using NSUserNotificationCenter. Notifications are coming while running code on eclipse. But, the issue is when I made app using py2app, Notifications are not coming. Moreover, the default page of error of open console and Terminate is coming. Please suggest some way, how to include Notification in dist generated by py2app, so that It will work on any other machine.
My setup.py is
from setuptools import setup
APP=['CC4Box.py']
DATA_FILES= [('',['config.cfg'])]
OPTIONS={'iconfile':'cc.icns','argv_emulation': True,'plist':{'CFBundleShortVersionString':'1.0'}}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app']
)
My notification code is:
def notify(title, subtitle, info_text, delay=0, sound=False, userInfo={}):
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
notification = NSUserNotification.alloc().init()
notification.setTitle_(title)
notification.setSubtitle_(subtitle)
notification.setInformativeText_(info_text)
notification.setUserInfo_(userInfo)
if sound:
notification.setSoundName_("NSUserNotificationDefaultSoundName")
notification.setDeliveryDate_(Foundation.NSDate.dateWithTimeInterval_sinceDate_(delay, Foundation.NSDate.date()))
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
def notificationBalloon(title,msg):
notify(title1, msg1,"", sound=False)
On eclipse, notifications are coming as expected, however, import error produced in lines:
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
but in terminal these lines are nicely run.
My guess is, .lookUpClass() should be resolved at runtime. Thus you don't actually want to include that class in your py2app. Unless you wrote this class yourself that it.
What you do want to include is objc and related libraries. Make sure it's in your virtualenv when you call py2app. If python -m pydoc objc works, so should python setup.py py2app.
If you are trying to create a pop-up window to notify the user of certain information, there are plenty of python modules for this purpose. Wx python is a good choice. Here is the documentation for pop-up windows:
http://wxpython.org/docs/api/wx.PopupWindow-class.html
EDIT: That won't get an apple notification in the way you want. Try this code. It uses a downloadable command line tool called terminal-notifier to make notifications, accessed through python via sub process:
import subprocess
def notification(title, subtitle, message):
subprocess.Popen(['terminal-notifier','-message',message,'-title',title,'-subtitle',subtitle])
notification(title = 'notification title', subtitle = 'subtitle', message = 'Hello World')
This should get the results you want, although to install it automatically you need to run a build in ruby. You could also get it to play sounds, change some ID parameters, and even tell it to run a shell command when you click on it. For more information go here, this is where you can get the source and the docs:
https://github.com/julienXX/terminal-notifier
(I edited the whole question to be more clear)
Hello,
I have never had any affairs with Python GUI libraries. I know there are plenty and well documented, but as I need only one single snippet, I would dislike to dive deep into documentations to seek for a way how to do it. If I am going to write a GUI program, I surely would do that, but this is needed only as a few lines for my ad hoc script.
What would be the easiest and the most straightforward way for me (GUI noob) to write in Python following piece of code? Less lines = more happiness.
Grab a JPEG picture by filename.
Display it's thumbnail.
Below the thumbnail display a textfield so the user can type in a caption.
Wait until user hits ENTER key on his/her keyboard. In that case, close and return the input.
...or wait until user hits DELETE key. In that case, close and return an information about the decision (to delete the picture).
Dependencies or Linux-only solutions are okay. I need to run this on Xubuntu machine. Any code snippets, please? I believe this is a matter of 5 minutes for someone skilled in Python GUI field. I would need to study loads of library docs. Thank you!
Below is a minimal python script that more or less fits the spec.
It requires python2 and pyqt4 packages to be installed, and it won't work with python3 (although it could quite easily be adapted to do so if necessary).
If the user types in a valid caption and presses enter, the script will return with status code 0 and print the caption to stdout; otherwise, if the user enters an invalid caption (empty or whitespace only), or simply closes the dialog without doing anything, the script will return with status code 1 and print nothing.
example bash usage:
$ CAPTION=$(python imgviewer.py image.jpg)
$ [ $? -eq 0 ] && echo $CAPTION
imgviewer.py:
import sys, os
from PyQt4 import QtGui, QtCore
class Dialog(QtGui.QDialog):
def __init__(self, path):
QtGui.QDialog.__init__(self)
self.viewer = QtGui.QLabel(self)
self.viewer.setMinimumSize(QtCore.QSize(400, 400))
self.viewer.setScaledContents(True)
self.viewer.setPixmap(QtGui.QPixmap(path))
self.editor = QtGui.QLineEdit(self)
self.editor.returnPressed.connect(self.handleReturnPressed)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.viewer)
layout.addWidget(self.editor)
def handleReturnPressed(self):
if self.editor.text().simplified().isEmpty():
self.reject()
else:
self.accept()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
args = app.arguments()[1:]
if len(args) == 1:
dialog = Dialog(args[0])
if dialog.exec_() == QtGui.QDialog.Accepted:
print dialog.editor.text().simplified().toLocal8Bit().data()
sys.exit(0)
else:
print 'ERROR: wrong number of arguments'
sys.exit(1)
There are several good GUI libraries for Python. The "standard" library that comes built-in with python is tkinter:http://wiki.python.org/moin/TkInter. Some says that wxPython is much more powerful and straightforward: http://www.wxpython.org/.
I think that you can start with wxPython, they have many many tutorials and examples you can dig into (just run the DEMO).
They have an example called "ImageBrowser" which might be a very good starting point.
Regarding the communication between the different apps, you can use "pipes" and "redirections" to communicate. But if everything is written in python, I think this is the wrong way to go, you can show the image form within your python script and get the result internally.
Im using Ubuntu 12.04. I want to access Rhythymbox using Python .
This is how I've proceeded so far:
Ive gone through this site
https://live.gnome.org/RhythmboxPlugins/WritingGuide , but it gives details on how to write plugins , which Im not interested in right now. Ive gone through a few tutorials which tells me to do this.
import dbus
session_bus = dbus.SessionBus()
proxy_obj = session_bus.get_object(
'org.gnome.Rhythmbox', '/org/gnome/Rhythmbox/Player')
But I am getting the following error
DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.Rhythmbox was not provided by any .service files.
Could someone please point me in the right direction of what I would like to achieve?
A workaround, used by lyricsdownloader.py, is:
import subprocess
import shlex
proc = subprocess.Popen(shlex.split('rhythmbox-client --no-start --print-playing-format %tt')))
title, err = proc.communicate()
Note: This does not work with Ubuntu 11.10, which shipped without rhythmbox-client.
This might be useful. https://github.com/aliva/rhythmbox-microblogger
It is a twitter plugin for RhythmBox. So instead of twitter and Gtk, you can just take the current song.
from gi.repository import RB
RB.RhythmDBPropType.TITLE will give enum which you can use to get the title.
I think that you've encountered a bug in Rhythmbox DBus interface described on Launchpad. Tracker says that fix is committed, but possibly your version doesn't have that fix.
I have been trying to figure out how to use the Dragonfly module. I have taken a look at the documentation, but I can't seem to figure out how to use it. I just want to be able to recognize a few phrases and act upon those phrases.
That's correct, this example will terminate. I've seen this particular example quite a bit, and it is missing a number of key features.
The first thing is that pythoncom is not imported. This provides a main loop for the program. The above
from dragonfly.all import Grammar, CompoundRule
# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
spec = "do something computer" # Spoken form of command.
def _process_recognition(self, node, extras): # Callback when command is spoken.
print "Voice command spoken."
# Create a grammar which contains and loads the command rule.
grammar = Grammar("example grammar") # Create a grammar to contain the command rule.
grammar.add_rule(ExampleRule()) # Add the command rule to the grammar.
grammar.load() # Load the grammar.
while True:
pythoncom.PumpWaitingMessages()
sleep(.1)
First, in case you're using Linux, you should know that Dragonfly only works with Windows Speech Recognition or Dragon NaturallySpeaking + Natlink. (It is possible to get it working on Linux with a virtual machine and Aenea, but that seems out of the scope of this question.)
If you're using it with WSR, it should be as simple as making sure that Dragonfly is in your Python path and calling the following at the end of your main script:
while True:
pythoncom.PumpWaitingMessages()
time.sleep(0.1)
If you're using it with Dragon NaturallySpeaking, follow the link above to the Natlink website and follow the instructions there to install and activate Natlink before trying to use Dragonfly. Once it is installed (use all the defaults), you should be able to put Dragonfly scripts in your C:\NatLink\NatLink\MacroSystem folder and have them activate automatically when you start Dragon NaturallySpeaking.
I find the usage example given in this document to be pretty simple and self-explaining:
A very simple example of Dragonfly usage is to create a static voice
command with a callback that will be called when the command is
spoken. This is done as follows: ::
from dragonfly.all import Grammar, CompoundRule
# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
spec = "do something computer" # Spoken form of command.
def _process_recognition(self, node, extras): # Callback when command is spoken.
print "Voice command spoken."
# Create a grammar which contains and loads the command rule.
grammar = Grammar("example grammar") # Create a grammar to contain the command rule.
grammar.add_rule(ExampleRule()) # Add the command rule to the grammar.
grammar.load() # Load the grammar.