Hi I'm trying to use a python gtk script under python 2.7.3; on Linux (under X11) and it needs to load images into pixbufs from disk.
However, python returns a glib.GError: "Couldn't recognize the image file format" regardless of what type of file I try to open;
eg: with: pixbuf = gtk.gdk.pixbuf_new_from_file( filename )
I can do a gtk.gdk.pixbuf_get_formats(), and in the list of dictionaries which is returned, the formats I have tried to load are listed .png, .ppm, .jpg.
When I try a gtk.gdk.pixbuf_get_file_info( filename ), though, it returns None.
Other GTK based programs such as Gimp, load these same images just fine; and gtk scripts that don't load icons from disk, but which draw buttons -- etc. work just fine.
How would I search for the cause of this malfunction?
Am I missing some kind of a mime-type file ?
Is there an alternate path using other gtk function calls that might accomplish the loading another way?
This works for me:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gtk
def win_with_image():
pixbuf = gtk.gdk.pixbuf_new_from_file("photo.png")
print pixbuf
win = gtk.Window(gtk.WINDOW_TOPLEVEL)
image = gtk.Image()
image.set_from_pixbuf(pixbuf)
win.add(image)
win.connect("destroy", gtk.main_quit)
win.show_all()
if __name__ == '__main__':
win_with_image()
gtk.main()
If this doesn`t work for you, try to:
start google and type your error and choose the second link (http://aptosid.com/index.php?name=PNphpBB2&file=viewtopic&t=2246), in general this helps almost always.
reinstall libglib
install gtk (maybe some graphical libs - libpng, libjpeg, f.e.)
reinstall python/gtk package
fix broken package repository
change files permissions
Related
I have a simple script which parses a file and loads it's contents to a database. I don't need a UI, but right now I'm prompting the user for the file to parse using raw_input which is most unfriendly, especially because the user can't copy/paste the path. I would like a quick and easy way to present a file selection dialog to the user, they can select the file, and then it's loaded to the database. (In my use case, if they happened to chose the wrong file, it would fail parsing, and wouldn't be a problem even if it was loaded to the database.)
import tkFileDialog
file_path_string = tkFileDialog.askopenfilename()
This code is close to what I want, but it leaves an annoying empty frame open (which isn't able to be closed, probably because I haven't registered a close event handler).
I don't have to use tkInter, but since it's in the Python standard library it's a good candidate for quickest and easiest solution.
Whats a quick and easy way to prompt for a file or filename in a script without any other UI?
Tkinter is the easiest way if you don't want to have any other dependencies.
To show only the dialog without any other GUI elements, you have to hide the root window using the withdraw method:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
Python 2 variant:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
You can use easygui:
import easygui
path = easygui.fileopenbox()
To install easygui, you can use pip:
pip3 install easygui
It is a single pure Python module (easygui.py) that uses tkinter.
Try with wxPython:
import wx
def get_path(wildcard):
app = wx.App(None)
style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
dialog = wx.FileDialog(None, 'Open', wildcard=wildcard, style=style)
if dialog.ShowModal() == wx.ID_OK:
path = dialog.GetPath()
else:
path = None
dialog.Destroy()
return path
print get_path('*.txt')
pywin32 provides access to the GetOpenFileName win32 function. From the example
import win32gui, win32con, os
filter='Python Scripts\0*.py;*.pyw;*.pys\0Text files\0*.txt\0'
customfilter='Other file types\0*.*\0'
fname, customfilter, flags=win32gui.GetOpenFileNameW(
InitialDir=os.environ['temp'],
Flags=win32con.OFN_ALLOWMULTISELECT|win32con.OFN_EXPLORER,
File='somefilename', DefExt='py',
Title='GetOpenFileNameW',
Filter=filter,
CustomFilter=customfilter,
FilterIndex=0)
print 'open file names:', repr(fname)
print 'filter used:', repr(customfilter)
print 'Flags:', flags
for k,v in win32con.__dict__.items():
if k.startswith('OFN_') and flags & v:
print '\t'+k
Using tkinter (python 2) or Tkinter (python 3) it's indeed possible to display file open dialog (See other answers here). Please notice however that user interface of that dialog is outdated and does not corresponds to newer file open dialogs available in Windows 10.
Moreover - if you're looking on way to embedd python support into your own application - you will find out soon that tkinter library is not open source code and even more - it is commercial library.
(For example search for "activetcl pricing" will lead you to this web page: https://reviews.financesonline.com/p/activetcl/)
So tkinter library will cost money for any application wanting to embedd python.
I by myself managed to find pythonnet library:
Overview here: http://pythonnet.github.io/
Source code here: https://github.com/pythonnet/pythonnet
(MIT License)
Using following command it's possible to install pythonnet:
pip3 install pythonnet
And here you can find out working example for using open file dialog:
https://stackoverflow.com/a/50446803/2338477
Let me copy an example also here:
import sys
import ctypes
co_initialize = ctypes.windll.ole32.CoInitialize
# Force STA mode
co_initialize(None)
import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import OpenFileDialog
file_dialog = OpenFileDialog()
ret = file_dialog.ShowDialog()
if ret != 1:
print("Cancelled")
sys.exit()
print(file_dialog.FileName)
If you also miss more complex user interface - see Demo folder
in pythonnet git.
I'm not sure about portability to other OS's, haven't tried, but .net 5 is planned to be ported to multiple OS's (Search ".net 5 platforms", https://devblogs.microsoft.com/dotnet/introducing-net-5/ ) - so this technology is also future proof.
If you don't need the UI or expect the program to run in a CLI, you could parse the filepath as an argument. This would allow you to use the autocomplete feature of your CLI to quickly find the file you need.
This would probably only be handy if the script is non-interactive besides the filepath input.
Another os-agnostic option, use pywebview:
import webview
def webview_file_dialog():
file = None
def open_file_dialog(w):
nonlocal file
try:
file = w.create_file_dialog(webview.OPEN_DIALOG)[0]
except TypeError:
pass # user exited file dialog without picking
finally:
w.destroy()
window = webview.create_window("", hidden=True)
webview.start(open_file_dialog, window)
# file will either be a string or None
return file
print(webview_file_dialog())
Environment: python3.8.6 on Mac - though I've used pywebview on windows 10 before.
I just stumbled on this little trick for Windows only: run powershell.exe from subprocess.
import subprocess
sys_const = ssfDESKTOP # Starts at the top level
# sys_const = 0x2a # Correct value for "Program Files (0x86)" folder
powershell_browse = "(new-object -COM 'Shell.Application')."
powershell_browse += "BrowseForFolder(0,'window title here',0,sys_const).self.path"
ret = subprocess.run(["powershell.exe",powershell_browse], stdout=subprocess.PIPE)
print(ret.stdout.decode())
Note the optional use of system folder constants. (There's an obscure typo in shldisp.h that the "Program Files (0x86)" constant was assigned wrong. I added a comment with the correct value. Took me a bit to figure that one out.)
More info below:
System folder constants
I'm trying to load a QSound file from a qrc file but I can't find a way to do it. Is it possible?
Something like:
sound = QSound(":/audio/my_sound.ogg")
sound.play()
Unlike pixmaps, this syntax doesn't work for audio.
I'll be using pyinstaller to package the scripts and it would be useful if there was a way to include the sound files in the exe as well.
First make sure you can play an ogg file...on my system I get a console error with the ogg file...so also with the ogg resource
QSound.play("my_sound.ogg") # Error decoding source file:my_sound.ogg
QSound.play(":/audio/my_sound.ogg") # Error decoding source file::/audio/my_sound.ogg
Using a wav file works for me, so it verifies QSound can indeed play from a resource.
import sys
from PyQt5.QtCore import QCoreApplication, QFile
from PyQt5.QtMultimedia import QSound
import resources # compiled via: pyrcc5 -o resources.py resources.qrc
if __name__ == '__main__':
app = QCoreApplication(sys.argv)
# QSound.play("test.wav") # Plays fine
# Using a wav file in the resource as follows gives the following results
# <!DOCTYPE RCC>
# <RCC version="1.0">
# <qresource prefix="audio">
# <file>test.wav</file>
# </qresource>
# </RCC>
QSound.play(":/audio/test.wav") # Plays fine
sound = QSound(":/audio/test.wav")
sound.play() # Plays fine
QSound(":/audio/test.wav").play() # no sound...no error
# QFile.copy(":/audio/my_sound.ogg", "temp.ogg") # Could also copy to a local file to make sure was found in resource
sys.exit(app.exec_())
I haven't heard of qsound but i know many sound player modules such as pygame,playsound etc you can see the syntax in there sites they support play, stop, pause and much more
I am using PIL to open a single image in the default image viewer:
from PIL import Image
img = Image.open('example.jpg')
img.show()
Does any Python module contain a function enabling opening multiple images in the current system's default image viewer? For instance when on OS X, Preview.app should open with the list of images in the sidebar. From the command line this is no problem at all:
$ open my_picture_number_*
Use case is that users should just be able to explore a few dozen images.
Use subprocess.run to run the operating system's default image viewing app. subprocess.run works a lot like a command line. You just need to know what the command is for the operating system you're on. For windows, "explorer" will do; for OS X, as you point out, it's "open." I'm not sure what it is for Linux, maybe "eog"?
So, your code would look like this:
import sys
import subprocess
def openImage(path):
imageViewerFromCommandLine = {'linux':'xdg-open',
'win32':'explorer',
'darwin':'open'}[sys.platform]
subprocess.run([imageViewerFromCommandLine, path])
I've tried to use #jgfoot's answer, which worked, but made my program hang after the viewer was launched. I've solved this issue by using subprocess.Popen instead, like this:
import sys
import subprocess
def openImage(path):
imageViewerFromCommandLine = {'linux':'xdg-open',
'win32':'explorer',
'darwin':'open'}[sys.platform]
subprocess.Popen([imageViewerFromCommandLine, path])
(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.
It seems that if I want to create a very basic Cocoa application with a dock icon and the like, I would have to use Xcode and the GUI builder (w/ PyObjC).
The application I am intending to write is largely concerned with algorithms and basic IO - and thus, not mostly related to Apple specific stuff.
Basically the application is supposed to run periodically (say, every 3 minutes) .. pull some information via AppleScript and write HTML files to a particular directory. I would like to add a Dock icon for this application .. mainly to showing the "status" of the process (for example, if there is an error .. the dock icon would have a red flag on it). Another advantage of the dock icon is that I can make it run on startup.
Additional bonus for defining the dock right-click menu in a simple way (eg: using Python lists of callables).
Can I achieve this without using Xcode or GUI builders but simply using Emacs and Python?
Install the latest py2app, then make a new directory -- cd to it -- in it make a HelloWorld.py file such as:
# generic Python imports
import datetime
import os
import sched
import sys
import tempfile
import threading
import time
# need PyObjC on sys.path...:
for d in sys.path:
if 'Extras' in d:
sys.path.append(d + '/PyObjC')
break
# objc-related imports
import objc
from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper
# all stuff related to the repeating-action
thesched = sched.scheduler(time.time, time.sleep)
def tick(n, writer):
writer(n)
thesched.enter(20.0, 10, tick, (n+1, writer))
fd, name = tempfile.mkstemp('.txt', 'hello', '/tmp');
print 'writing %r' % name
f = os.fdopen(fd, 'w')
f.write(datetime.datetime.now().isoformat())
f.write('\n')
f.close()
def schedule(writer):
pool = NSAutoreleasePool.alloc().init()
thesched.enter(0.0, 10, tick, (1, writer))
thesched.run()
# normally you'd want pool.drain() here, but since this function never
# ends until end of program (thesched.run never returns since each tick
# schedules a new one) that pool.drain would never execute here;-).
# objc-related stuff
class TheDelegate(NSObject):
statusbar = None
state = 'idle'
def applicationDidFinishLaunching_(self, notification):
statusbar = NSStatusBar.systemStatusBar()
self.statusitem = statusbar.statusItemWithLength_(
NSVariableStatusItemLength)
self.statusitem.setHighlightMode_(1)
self.statusitem.setToolTip_('Example')
self.statusitem.setTitle_('Example')
self.menu = NSMenu.alloc().init()
menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Quit', 'terminate:', '')
self.menu.addItem_(menuitem)
self.statusitem.setMenu_(self.menu)
def writer(self, s):
self.badge.setBadgeLabel_(str(s))
if __name__ == "__main__":
# prepare and set our delegate
app = NSApplication.sharedApplication()
delegate = TheDelegate.alloc().init()
app.setDelegate_(delegate)
delegate.badge = app.dockTile()
delegate.writer(0)
# on a separate thread, run the scheduler
t = threading.Thread(target=schedule, args=(delegate.writer,))
t.setDaemon(1)
t.start()
# let her rip!-)
AppHelper.runEventLoop()
Of course, in your real code, you'll be performing your own periodic actions every 3 minutes (rather than writing a temp file every 20 seconds as I'm doing here), doing your own status updates (rather than just showing a counter of the number of files written so far), etc, etc, but I hope this example shows you a viable starting point.
Then in Terminal.App cd to the directory containing this source file, py2applet --make-setup HelloWorld.py, python setup.py py2app -A -p PyObjC.
You now have in subdirectory dist a directory HelloWorld.app; open dist and drag the icon to the Dock, and you're all set (on your own machine -- distributing to other machines may not work due to the -A flag, but I had trouble building without it, probably due to mis-installed egg files laying around this machine;-). No doubt you'll want to customize your icon &c.
This doesn't do the "extra credit" thingy you asked for -- it's already a lot of code and I decided to stop here (the extra credit thingy may warrant a new question). Also, I'm not quite sure that all the incantations I'm performing here are actually necessary or useful; the docs are pretty latitant for making a pyobjc .app without Xcode, as you require, so I hacked this together from bits and pieces of example code found on the net plus a substantial amount of trial and error. Still, I hope it helps!-)
PyObjC, which is included with Mac OS X 10.5 and 10.6, is pretty close to what you're looking for.
Chuck is correct about PyObjC.
You should then read about this NSApplication method to change your icon.
-(void)setApplicationIconImage:(NSImage *)anImage;
For the dock menu, implement the following in an application delegate. You can build an NSMenu programmatically to avoid using InterfaceBuilder.
-(NSMenu *)applicationDockMenu:(NSApplication *)sender;