I want to access the text in the clipboard from within ipython.
I got this far (not even sure if this is the best way, just found by poking around in ipython magics sources):
import IPython
from IPython.core.hooks import clipboard_get
ip = IPython.get_ipython()
my_string = clipboard_get(ip)
And it kinda works for stuff I've copied manually, but I want to get the "other" clipboard - the one you get when you use the middle mouse click. The selection buffer or whatever it's called.
Any ideas?
You can get X Window's "middle mouse button" selection (called the PRIMARY selection) through Tkinter:
import Tkinter # Replace "Tkinter" with "tkinter" for Python 3.x.
tk = Tkinter.Tk()
tk.withdraw()
print(tk.selection_get())
Another solution is to run xclip and get its output. (If you don't have xclip installed it can be found in most Linux distributions' package repositories.)
import subprocess
print(subprocess.check_output(['xclip', '-o', '-selection', 'PRIMARY']))
Related
I am trying to set an application icon (python3 / tkinter) like this:
Interface()
root.title("Quicklist Editor")
root.iconbitmap('#/home/jacob/.icons/qle_icon.ico')
root.resizable(0, 0)
root.mainloop()
no matter what I do, I keep getting an error message (Idle), saying:
return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: error reading bitmap file "/home/jacob/.icons/qle_icon.ico"
What am I doing wrong?
The problem is not the code, but the icon. I tried creating an xbm with another program than Gimp (some KDE icon editor), and although it looks terrifyingly ugly, it does show an icon.
I guess I have to find a creator that gives an "understandable" icon for my Python program.
Edit
The iconbitmap method turned out to be black and white only, so it was useless after all.
After a long search, I found the solution to set the color of an application's icon for Python 3 (on Linux). I found it here:
root = Tk()
img = PhotoImage(file='your-icon')
root.tk.call('wm', 'iconphoto', root._w, img)
This is an old question, and there is lots of stuff written about it on the web, but all of it is either incorrect or incomplete, so having gotten it to work I thought it would be good to record my actual working code here.
First, you'll need to create an icon and save it in two formats: Windows "ico" and Unix "xbm". 64 x 64 is a good size. XBM is a 1-bit format--pixels just on or off, so no colors, no grays. Linux implementations of tkinter only accept XBM even though every Linux desktop supports real icons, so you're just out of luck there. Also, the XBM spec is ambiguous about whether "on" bits represent black or white, so you may have to invert the XBM for some desktops. Gimp is good for creating these.
Then to put the icon in your titlebar, use this code (Python 3):
import os
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("My Application")
if "nt" == os.name:
root.wm_iconbitmap(bitmap = "myicon.ico")
else:
root.wm_iconbitmap(bitmap = "#myicon.xbm")
root.mainloop()
This will allow you to use PNG files as icons, and it does render color. I tested it on Xubuntu 14.04, 32-bit with Python 3.4 (root is your Tk object):
import sys, os
program_directory=sys.path[0]
root.iconphoto(True, PhotoImage(file=os.path.join(program_directory, "test.png")))
(Finding program directory is important if you want it to search for test.png in the same location in all contexts. os.path.join is a cross-platform way to add test.png onto the program directory.)
If you change True to False then it won't use the same icon for windows that aren't the main one.
Please let me know if this works on Windows and Mac.
I tried this, and I couldn't get it to work using Windows 7.
Found a fix.
Use Jacob's answer, but the file has to be a .gif if you're using my OS, (Windows 7) it appears.
Make a 64x64 gif using MS paint, save it, use the file path and bingo, works.
I hope this helps you for cross-platform ability
LOGO_PATH="pic/logo.ico"
LOGO_LINUX_PATH="#pic/logo_1.xbm" #do not forget "#" symbol and .xbm format for Ubuntu
root = Tk()
if detect_screen_size().detect_os()=="Linux":
root.iconbitmap(LOGO_LINUX_PATH)
else:
root.iconbitmap(LOGO_PATH)
Simply using an r string to convert the directory into raw text worked for me:
ex:
app.iconbitmap(r'enter your path here')
In my case, Ubuntu 20.04, python 3.6 (conda), the command iconbitmap(bitmap=icon_path) failed w/ this error. In the end, I put the command w/in a try-except block and it worked; I can see the colorful image.
I'm surprised to see this is such an old question with no good answers, not in eight years! I too want my own icon for my "quickie" tkinter program.
What does work for me on Linux and Python3:
#!/usr/bin/env python
import tkinter
from PIL import Image, ImageTk
root = tkinter.Tk()
im = Image.open('junk.png')
photo = ImageTk.PhotoImage(im)
root.wm_iconphoto(True, photo)
root.mainloop()
The key seems to be using Image and ImageTk. I found zero solutions that worked without these.
I'm trying to set focus to a window using python-wnck.
The only docs I could find related to this library are from https://developer.gnome.org/libwnck/stable/WnckWindow.html
Using some code I found on another question here at SO, I was able to search for windows using the window title, but I'm not sure how to get a window to focus. From the above docs I found the function:
wnck_window_activate(WnckWindow *window, guint32 timestamp);
So in python I tried using this function like "window.activate(0)", but this appears to fail, the icon on my taskbar flashed but it doesn't get focus.In the terminal I get the message:
(windowTest.py:17485): Wnck-WARNING: Received a timestamp of 0; window activation may not function properly
So I think I may actually need to put in a valid timestamp but not sure how to get this.
This is the code Im using sofar:
import pygtk
pygtk.require('2.0')
import gtk
import wnck
import re
import sys
screen = wnck.screen_get_default()
while gtk.events_pending():
gtk.main_iteration()
titlePattern = re.compile('.*Geany.*')
windows = screen.get_windows()
for w in windows:
if titlePattern.match(w.get_name()):
print w.get_name()
w.activate(0)
The solution was actually pretty simpleI just needed to "import time" then pass "int(time.time())" into the activate function
Working code:
import pygtk
pygtk.require('2.0')
import gtk
import wnck
import re
import sys
import time
screen = wnck.screen_get_default()
while gtk.events_pending():
gtk.main_iteration()
titlePattern = re.compile('.*Geany.*')
windows = screen.get_windows()
for w in windows:
if titlePattern.match(w.get_name()):
print w.get_name()
w.activate(int(time.time()))
To get away from the Wnck-WARNING, you need to send a valid timestamp with the w.activate() function. The way that I found to do this is to use:
now = gtk.gdk.x11_get_server_time(gtk.gdk.get_default_root_window())
w.activate(now)
There really should be an easier way to do this, or wnck should allow a timestamp of 0 to mean now like most of the gtk libraries use.
Is there a messagebox class where I can just display a simple message box without a huge GUI library or any library upon program success or failure. (My script only does 1 thing).
Also, I only need it to run on Windows.
You can use the ctypes library, which comes installed with Python:
import ctypes
MessageBox = ctypes.windll.user32.MessageBoxW
MessageBox(None, 'Hello', 'Window title', 0)
Above code is for Python 3.x. For Python 2.x, use MessageBoxA instead of MessageBoxW as Python 2 uses non-unicode strings by default.
There are also a couple prototyped in the default libraries without using ctypes.
Simple message box:
import win32ui
win32ui.MessageBox("Message", "Title")
Other Options
if win32ui.MessageBox("Message", "Title", win32con.MB_YESNOCANCEL) == win32con.IDYES:
win32ui.MessageBox("You pressed 'Yes'")
There's also a roughly equivalent one in win32gui and another in win32api. Docs for all appear to be in C:\Python{nn}\Lib\site-packages\PyWin32.chm
The PyMsgBox module uses Python's tkinter, so it doesn't depend on any other third-party modules. You can install it with pip install pymsgbox.
The function names are similar to JavaScript's alert(), confirm(), and prompt() functions:
>>> import pymsgbox
>>> pymsgbox.alert('This is an alert!')
>>> user_response = pymsgbox.prompt('What is your favorite color?')
A quick and dirty way is to call OS and use "zenity" command (subprocess module should be included by default in any python distribution, zenity is also present in all major linux). Try this short example script, it works in my Ubuntu 14.04.
import subprocess as SP
# call an OS subprocess $ zenity --entry --text "some text"
# (this will ask OS to open a window with the dialog)
res=SP.Popen(['zenity','--entry','--text',
'please write some text'], stdout=SP.PIPE)
# get the user input string back
usertext=str(res.communicate()[0][:-1])
# adjust user input string
text=usertext[2:-1]
print("I got this text from the user: %s"%text)
See the zenity --help for more complex dialogs
You can also use the messagebox class from tkinter:
from tkinter import messagebox
unless tkinter is that huge GUI you want to avoid.
Usage is simple, ie:
messagebox.FunctionName(title, message [, options])
with FuntionName in (showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, askretrycancel).
This one with tkinter.
from tkinter import * #required.
from tkinter import messagebox #for messagebox.
App = Tk() #required.
App.withdraw() #for hide window.
print("Message Box in Console")
messagebox.showinfo("Notification", "Hello World!") #msgbox
App.mainloop() #required.
I need to get focus to a specified window, and the only way I'm seeing on my head, is minimizing all windows on front of it until I get the right one...
How can I do it?
Windows 7, and no specific toolkit....
Every type of window, for example, firefox and console command
You'll need to enumerate through the windows and match the title of the window to get the one you want. The code below searches for a window with "firefox" in the title and sets the focus:
import win32gui
toplist = []
winlist = []
def enum_callback(hwnd, results):
winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
win32gui.EnumWindows(enum_callback, toplist)
firefox = [(hwnd, title) for hwnd, title in winlist if 'firefox' in title.lower()]
# just grab the first window that matches
firefox = firefox[0]
# use the window handle to set focus
win32gui.SetForegroundWindow(firefox[0])
To minimize the window, the following line:
import win32con
win32gui.ShowWindow(firefox[0], win32con.SW_MINIMIZE)
You'll need to enumerate through the windows and match the title of the window to get the one you want. The code below searches for a window with "firefox" in the title and sets the focus
To minimize the window use the following line:
def enumHandler(hwnd, lParam):
if 'firefox' in win32gui.GetWindowText(hwnd):
win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
win32gui.EnumWindows(enumHandler, None)
This works for Windows 10, Python3.5 32bit, pywin32‑223.
I reported the above case, but an error occurred.
Traceback (most recent call last):
TypeError: The object is not a PyHANDLE object
I'm assuming from the question, that you want to write a generic to that can work with any window from any application.
You might want to try the Python Win32 GUI Automation library. I haven't used it but sounds like it might be what you are looking for. If that doesn't work, your best option might be forgo python and use a tool like AutoIt that provides built in support for window manipulation.
If neither of those solutions work you will probable have to directly invoke windows api. I do not know if the win32api package wraps the necessary functionality, otherwise you will have write a python module in c/c++.
If this kind of functionality is available in the .net api, you could use IronPython.
Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon.
This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities.
Update:
This is intended to run in the background and alert the user when certain conditions are met, I figure that the easiest way to alert the user would be to produce a pop-up, as it needs to be handled immediately, and other options such as just logging, or sending an email are not efficient enough.
what about this:
import win32api
win32api.MessageBox(0, 'hello', 'title')
Additionally:
win32api.MessageBox(0, 'hello', 'title', 0x00001000)
will make the box appear on top of other windows, for urgent messages. See MessageBox function for other options.
For those of us looking for a purely Python option that doesn't interface with Windows and is platform independent, I went for the option listed on the following website:
https://pythonspot.com/tk-message-box/ (archived link: https://archive.ph/JNuvx)
# Python 3.x code
# Imports
import tkinter
from tkinter import messagebox
# This code is to hide the main tkinter window
root = tkinter.Tk()
root.withdraw()
# Message Box
messagebox.showinfo("Title", "Message")
You can choose to show various types of messagebox options for different scenarios:
showinfo()
showwarning()
showerror ()
askquestion()
askokcancel()
askyesno ()
askretrycancel ()
edited code per my comment below
You can use PyAutoGui to make alert boxes
First install pyautogui with pip:
pip install pyautogui
Then type this in python:
import pyautogui as pag
pag.alert(text="Hello World", title="The Hello World Box")
Here are more message boxes, stolen from Javascript:
confirm()
With Ok and Cancel Button
prompt()
With Text Input
password()
With Text Input, but typed characters will be appeared as *
GTK may be a better option, as it is cross-platform. It'll work great on Ubuntu, and should work just fine on Windows when GTK and Python bindings are installed.
from gi.repository import Gtk
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK, "This is an INFO MessageDialog")
dialog.format_secondary_text(
"And this is the secondary text that explains things.")
dialog.run()
print "INFO dialog closed"
You can see other examples here. (pdf)
The arguments passed should be the gtk.window parent (or None), DestroyWithParent, Message type, Message-buttons, title.
You can use win32 library in Python, this is classical example of OK or Cancel.
import win32api
import win32com.client
import pythoncom
result = win32api.MessageBox(None,"Do you want to open a file?", "title",1)
if result == 1:
print 'Ok'
elif result == 2:
print 'cancel'
The collection:
win32api.MessageBox(0,"msgbox", "title")
win32api.MessageBox(0,"ok cancel?", "title",1)
win32api.MessageBox(0,"abort retry ignore?", "title",2)
win32api.MessageBox(0,"yes no cancel?", "title",3)
Start an app as a background process that either has a TCP port bound to localhost, or communicates through a file -- your daemon has the file open, and then you echo "foo" > c:\your\file. After, say, 1 second of no activity, you display the message and truncate the file.