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.
Related
I was hoping somebody could point me in the right direction for a project I would like to do. My intention is simple, to have a GUI that allows a user to input a string, that string fills into a pre-determined line of command line text, runs through the command line and returns what is printed on the command line screen. I've been leaning toward using Python for this but I am still not sure about the syntax that will accomplish even the first part, where a user will input a string and that string will run through the line of command line text. Any sort of input would be greatly appreciated!
This is a simple GUI using tkinter for python
try:
import tkinter as tk # python v3
except:
import Tkinter as tk # python v2
# This function is called when the submit button is clicked
def submit_callback(input_entry):
print("User entered : " + input_entry.get())
return None
####################### GUI ###########################
root = tk.Tk()
root.geometry('300x150') #Set window size
# Heading
heading = tk.Label(root, text="A simple GUI")
heading.place(x = 100, y = 0)
input_label = tk.Label(root, text="Enter some text")
input_label.place(x = 0, y = 50)
input_entry = tk.Entry(root)
input_entry.place(x = 100, y = 50)
submit_button = tk.Button(root, text = "Submit", command = lambda: submit_callback(input_entry))
submit_button.place(x = 200, y = 90)
root.mainloop()
#############################################################
Developing a GUI is a big project for python beginners, there are several possibilities to do this. If you want to seriously develop GUI applications in Python I would recommend you to try Qt4 or Qt5 via pyside or pyqt. You may need one or more tutorials and maybe some problems to get your first working GUI applications, but you will be able to build any kind of professional cross-platform applications using this libraries.
With running command line text, you mean system commands or python commands? If you want to run system commands, I would recommend you to write a short python script, that handles user input (within the python commandline) and passes it to the system using subprocess (from subprocess import call).
If you have done your first simple textform in pyqt and the script that handles user input try to connect them by wrapping the Qt application around the commandline script. If you just looking for a quick and dirty solution there are several libraries, that support some easy to setup GUI frames or webinterfaces (to run in the browser on the local machine). But if you are a programming beginner I would highly recommend to split this into twor or three minor projects, to keep the frustration level low ;).
Edit Python2 vs Python3: pyqt and pyside are available for both python2 and python3 (as the most, but not all libraries) so your choice between py2 and py3 is on your own. The Syntax is almost the same (except the print() command), but the libraries you install are only working in the version you installed them.
If you are working on a linux machine you can easily install both versions in parallel if you want to make sure the right version is called you can specify the command such as python2 or python3 instead of running the default with python
Edit2 handle user input:
from subprocess import check_output
def predefined_command(user_input):
command = ['net', 'user', '/domain', user_input]
answer = check_output(command, args)
decoded = answer.decode('utf8')
return answer
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']))
i am on mac os x 10.8, using the integrated python 2.7.
i try to learn about tkinter with tutorials like this for python 2.7 (explicitly not 3)
they propose the following code:
from tkinter import *
import tkinter.messagebox
however, this brings up the error:
ImportError: No module named tkinter
using import.Tkinter with a capital t seems to work, but further commands like
import Tkinter.messagebox
don't (neither does tkinter.messagebox).
I've had this problem with lots of tutorials. what's the thing with the capital / non-capital "T", and how do i get my python to work like it does in the tutorials? Thanks in advance!
Tkinter (capitalized) refers to versions <3.0.
tkinter (all lowecase) refers to versions ≥3.0.
Source: https://wiki.python.org/moin/TkInter
In Tkinter (uppercase) you do not have messagebox.
You can use Tkinter.Message or import tkMessageBox
This code is an example taken from this tutorial:
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def hello():
tkMessageBox.showinfo("Say Hello", "Hello World")
B1 = Tkinter.Button(top, text = "Say Hello", command = hello)
B1.pack()
top.mainloop()
Your example code refers to a python installation >= py3.0. In Python 3.x the old good Tkinter has been renamed tkinter.
For python 2.7 it is Tkinter, however in 3.3.5 it is tkinter.
For python 2.7 use Cap Letters Tkinter but for >3.0 use small letter tkinter
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 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.