Jak mogę utworzyć proste okno wiadomości w Pythonie?

Szukam takiego samego efektu jak alert() w JavaScript.

Napisałem dziś po południu prosty interpreter internetowy, używając Twisted.www. Zasadniczo przesyłasz blok kodu Pythona przez formularz, a klient przychodzi, chwyta go i wykonuje. Chcę być w stanie zrobić prosty komunikat popup, bez konieczności ponownego pisania całego kodu boilerplate wxPython lub TkInter za każdym razem(ponieważ kod jest przesyłany przez formularz, a następnie znika).

Próbowałem tkMessageBox:

import tkMessageBox
tkMessageBox.showinfo(title="Greetings", message="Hello World!")

Ale to otwiera inne okno w tle z ikoną tk. Nie chcę tego. Szukałem jakiegoś prostego kodu wxPython, ale zawsze wymagało to skonfigurowania klasy i wprowadzenia pętli aplikacji itp. Czy nie ma prostego, wolnego od haczyków sposobu tworzenia skrzynki komunikatów w Pythonie?

Author: Carson Myers, 2010-06-03

12 answers

Możesz użyć kodu importowego i jednolinijkowego, takiego jak:

import ctypes  # An included library with Python install.   
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

Lub zdefiniuj funkcję (Mbox) w ten sposób:

import ctypes  # An included library with Python install.
def Mbox(title, text, style):
    return ctypes.windll.user32.MessageBoxW(0, text, title, style)
Mbox('Your title', 'Your text', 1)

Zauważ, że style są następujące:

##  Styles:
##  0 : OK
##  1 : OK | Cancel
##  2 : Abort | Retry | Ignore
##  3 : Yes | No | Cancel
##  4 : Yes | No
##  5 : Retry | No 
##  6 : Cancel | Try Again | Continue
Baw się dobrze!

Uwaga: edytowane w celu użycia MessageBoxW zamiast MessageBoxA

 179
Author: user2140260,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-17 19:22:45

Spojrzałeś na easygui ?

import easygui

easygui.msgbox("This is a message!", title="simple gui")
 42
Author: Ryan Ginstrom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-03 05:54:46

Możesz również ustawić inne okno przed wycofaniem go, aby ustawić swoją wiadomość

#!/usr/bin/env python

from Tkinter import *
import tkMessageBox

window = Tk()
window.wm_withdraw()

#message at x:200,y:200
window.geometry("1x1+200+200")#remember its .geometry("WidthxHeight(+or-)X(+or-)Y")
tkMessageBox.showerror(title="error",message="Error Message",parent=window)

#centre screen message
window.geometry("1x1+"+str(window.winfo_screenwidth()/2)+"+"+str(window.winfo_screenheight()/2))
tkMessageBox.showinfo(title="Greetings", message="Hello World!")
 21
Author: Lewis Cowles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-16 11:03:53

Prezentowany kod jest w porządku! Wystarczy jawnie utworzyć "inne okno w tle" i ukryć je za pomocą tego kodu:

import Tkinter
window = Tkinter.Tk()
window.wm_withdraw()

Tuż przed Twoim messagebox.

 15
Author: Jotaf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-25 22:44:20

Na Macu biblioteka standardowa Pythona posiada moduł o nazwie EasyDialogs. Istnieje również (oparta na ctypes) wersja windows na http://www.averdevelopment.com/python/EasyDialogs.html

Jeśli ma to dla Ciebie znaczenie: używa natywnych okien dialogowych i nie zależy od Tkintera, jak wspomniany już easygui, ale może nie mieć tak wielu funkcji.

 9
Author: Steven,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-03 11:52:43

W systemie Windows możesz używać ctypes z biblioteką user32 :

from ctypes import c_int, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT
prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)

MessageBox()
MessageBox(text="Spam, spam, spam")
MessageBox(flags=2, text="foo bar")
 8
Author: YOU,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 00:41:36

Moduł PyMsgBox robi dokładnie to. Posiada funkcje skrzynki komunikatów, które są zgodne z konwencjami nazewnictwa JavaScript: alert (), confirm (), prompt () i password () (które są prompt (), ale używa * podczas wpisywania). Funkcja ta wywołuje funkcję block, dopóki użytkownik nie kliknie przycisku OK/Cancel. Jest to wieloplatformowy, czysty moduł Pythona bez zależności.

Zainstaluj za pomocą: pip install PyMsgBox

Przykładowe użycie:

>>> import pymsgbox
>>> pymsgbox.alert('This is an alert!', 'Title')
>>> response = pymsgbox.prompt('What is your name?')

Pełna dokumentacja na http://pymsgbox.readthedocs.org/en/latest/

 6
Author: Al Sweigart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-04 00:09:45
import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

Ostatni numer (tutaj 1) można zmienić, aby zmienić styl okna(nie tylko przyciski!):

## Button styles:
# 0 : OK
# 1 : OK | Cancel
# 2 : Abort | Retry | Ignore
# 3 : Yes | No | Cancel
# 4 : Yes | No
# 5 : Retry | No 
# 6 : Cancel | Try Again | Continue

## To also change icon, add these values to previous number
# 16 Stop-sign icon
# 32 Question-mark icon
# 48 Exclamation-point icon
# 64 Information-sign icon consisting of an 'i' in a circle

Na przykład,

ctypes.windll.user32.MessageBoxW(0, "That's an error", "Warning!", 16)

Da to.

 2
Author: Arkelis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-19 20:41:36

Użyj

from tkinter.messagebox import *
Message([master], title="[title]", message="[message]")

Okno główne musi zostać utworzone wcześniej. To dla Pythona 3. To nie jest fot wxPython, ale dla tkinter.

 1
Author: HD1920,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-22 09:16:41
import sys
from tkinter import *
def mhello():
    pass
    return

mGui = Tk()
ment = StringVar()

mGui.geometry('450x450+500+300')
mGui.title('My youtube Tkinter')

mlabel = Label(mGui,text ='my label').pack()

mbutton = Button(mGui,text ='ok',command = mhello,fg = 'red',bg='blue').pack()

mEntry = entry().pack 
 1
Author: Robert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-11 13:19:39

Nie najlepszy, oto moja podstawowa skrzynka z wiadomościami używająca tylko tkinter.

#Python 3.4
from    tkinter import  messagebox  as  msg;
import  tkinter as      tk;

def MsgBox(title, text, style):
    box = [
        msg.showinfo,       msg.showwarning,    msg.showerror,
        msg.askquestion,    msg.askyesno,       msg.askokcancel,        msg.askretrycancel,
];

tk.Tk().withdraw(); #Hide Main Window.

if style in range(7):
    return box[style](title, text);

if __name__ == '__main__':

Return = MsgBox(#Use Like This.
    'Basic Error Exemple',

    ''.join( [
        'The Basic Error Exemple a problem with test',                      '\n',
        'and is unable to continue. The application must close.',           '\n\n',
        'Error code Test',                                                  '\n',
        'Would you like visit http://wwww.basic-error-exemple.com/ for',    '\n',
        'help?',
    ] ),

    2,
);

print( Return );

"""
Style   |   Type        |   Button      |   Return
------------------------------------------------------
0           Info            Ok              'ok'
1           Warning         Ok              'ok'
2           Error           Ok              'ok'
3           Question        Yes/No          'yes'/'no'
4           YesNo           Yes/No          True/False
5           OkCancel        Ok/Cancel       True/False
6           RetryCancal     Retry/Cancel    True/False
"""
 0
Author: Creuil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-15 20:12:37

Sprawdź mój moduł Pythona: pip install quickgui (wymaga wxPython, ale nie wymaga znajomości wxPython) https://pypi.python.org/pypi/quickgui

Może tworzyć dowolną liczbę wejść, (ratio, checkbox, inputbox), automatycznie układać je na pojedynczym gui.

 0
Author: Jerry T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-28 16:21:27