Python에서 간단한 메시지 상자를 어떻게 만들 수 있습니까?


119

alert()JavaScript에서 와 동일한 효과를 찾고 있습니다.

오늘 오후에 Twisted.web을 사용하여 간단한 웹 기반 인터프리터를 작성했습니다. 기본적으로 양식을 통해 Python 코드 블록을 제출하면 클라이언트가 가져 와서 실행합니다. 매번 상용구 wxPython 또는 TkInter 코드 전체를 다시 작성할 필요없이 간단한 팝업 메시지를 만들 수 있기를 원합니다 (코드가 양식을 통해 제출 된 다음 사라집니다).

tkMessageBox를 시도했습니다.

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

그러나 이것은 tk 아이콘이있는 백그라운드에서 다른 창을 엽니 다. 나는 이것을 원하지 않는다. 간단한 wxPython 코드를 찾고 있었지만 항상 클래스를 설정하고 앱 루프 등을 입력해야했습니다. Python에서 메시지 상자를 만드는 간단하고 캐치없는 방법이 없습니까?

답변:


257

다음과 같이 가져 오기 및 한 줄 코드를 사용할 수 있습니다.

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

또는 다음과 같이 함수 (Mbox)를 정의하십시오.

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)

스타일은 다음과 같습니다.

##  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

즐기세요!

참고 : MessageBoxW대신 사용하도록 편집MessageBoxA


2
내가 찾던 바로 그것. OP도 소리처럼 들립니다. 답으로 표시해야합니다!
— CodeMonkey 2013

3
Meh. 내가 너무 빨리 말 했나봐. 제목과 메시지 모두에 대해 하나의 문자 만 받고 있습니다. 이상한 ...
— CodeMonkey 2010

18
MessageBoxA 대신 MessageBoxW를 사용해야했습니다.
— CodeMonkey 2013

9
파이썬 3의 @CodeMonkey, MessageBoxA 대신 MessageBoxW 사용
— Oliver Ni

2
참고 : 내 팝업이 영어로되어 있지 않았으며 사용자 Burhan Khalid의 답변
— Ari

50

당신이 봤어 에는 EasyGUI ?

import easygui

easygui.msgbox("This is a message!", title="simple gui")

7
이것은 tkinter가 아니며, 기본적으로 제공되지 않습니다. 이상합니다. 누가 불필요한 종속성을 가져 오는 간단한 기능을 도입하는 데 관심이 있습니까?
— Tebe 2012

7
실제로 gekannt, easygui는 tkinter를 둘러싼 래퍼입니다. 예, 추가 종속성이지만 단일 Python 파일입니다. 일부 개발자는 단순한 GUI를 구현하기 위해 종속성이 가치가 있다고 생각할 수 있습니다.
— Ryan Ginstrom

22

또한 취소하기 전에 다른 창을 배치하여 메시지를 배치 할 수 있습니다.

#!/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!")

3
어떤 방법은 우리가 PROSS 할 필요가 없습니다 그래서, 거기에 확인 에서 버튼 tkMessageBox을 하고 자동으로 처리?
— varsha_holla

@varsha_holla 메시지 상자가 작동하는 방식이 아닙니다. 타이머가있는 표준 창을 만드는 방법을 살펴볼 수 있습니다.
— Kelly Elton

19

제시 한 코드는 괜찮습니다! 다음 코드를 사용하여 "백그라운드의 다른 창"을 명시 적으로 만들고 숨기면됩니다.

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

메시지 함 바로 앞.


4
깔끔하게 종료하려면 끝에 "window.destroy ()"를 추가해야했습니다.
— kuzzooroo 2014 년

11

PyMsgBox 모듈은 정확히 이것을합니다. JavaScript의 이름 지정 규칙을 따르는 메시지 상자 함수 : alert (), confirm (), prompt () 및 password () (prompt ()이지만 입력 할 때 *를 사용함). 이러한 함수 호출은 사용자가 확인 / 취소 버튼을 클릭 할 때까지 차단됩니다. 종속성이없는 크로스 플랫폼, 순수 Python 모듈입니다.

다음으로 설치 : pip install PyMsgBox

샘플 사용법 :

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

http://pymsgbox.readthedocs.org/en/latest/의 전체 문서


이상한. 종속성이 없다고 썼지 만 사용하려고하면 인쇄됩니다AssertionError: Tkinter is required for pymsgbox
— shitpoet

나는 그것을 변경해야한다 : pymsgbox는 tkinter가 속한 표준 라이브러리 외부에 의존성이 없다. 어떤 버전의 Python과 어떤 OS를 사용하고 있습니까?
— Al Sweigart

죄송합니다. 저는 Python에서 멍청한 사람입니다. 모든 Python lib가를 통해 설치된다고 생각 pip했지만 실제로 libs의 일부는 시스템 패키지 관리자를 사용하여 다른 방식으로 설치됩니다. 그래서 python-tk패키지 관리자를 사용하여 설치했습니다 . Debian에서 Python 2.7을 사용하고 있습니다.
— shitpoet 19-01-10

offtopic :하지만 PyMsgBox / Tk에 의해 생성 된 메시지 상자는 제 데비안에서 꽤보기 흉하게 보입니다
— shitpoet

10

Windows에서는 user32 라이브러리와 함께 ctypes를 사용할 수 있습니다 .

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")


7
import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

마지막 숫자 (여기서는 1)를 변경하여 창 스타일을 변경할 수 있습니다 (단추뿐만 아니라!) :

## 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

예를 들면

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

이것을 줄 것입니다 :

여기에 이미지 설명 입력


1

사용하다

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

마스터 창은 이전에 만들어야합니다. 이것은 Python 3 용입니다. 이것은 wxPython 용이 아니라 tkinter 용입니다.


Robert의 대답에 대한 "import *"에 대한 내 의견을 참조하십시오.
— Jürgen A. Erhard

1
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 

또한 모든 사람들의 사랑이 PEP8과 pythonic이므로 "import *"를 중단하십시오. 나쁘다, 응?
— Jürgen A. Erhard

1

또한 취소하기 전에 다른 창을 배치하여 메시지를 배치 할 수 있습니다.

from tkinter import *
import tkinter.messagebox

window = Tk()
window.wm_withdraw()

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

# center screen message
window.geometry(f"1x1+{round(window.winfo_screenwidth() / 2)}+{round(window.winfo_screenheight() / 2)}")
tkinter.messagebox.showinfo(title="Greetings", message="Hello World!")

참고 : 이것은 tkinter가 python 2 이후로 변경되었으므로 Lewis Cowles의 대답은 Python 3ified입니다.

try:
    import tkinter
    import tkinter.messagebox
except ModuleNotFoundError:
    import Tkinter as tkinter
    import tkMessageBox as tkinter.messagebox

0

최고는 아니지만 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
"""

가져 오기 형식은 완전히 괴롭습니다. 혹시 오래된 COBOL 또는 FORTRAN 프로그래머입니까? ;-)
— Jürgen A. Erhard 2016 년

0

내 파이썬 모듈을 확인하십시오 : pip install quickgui (wxPython이 필요하지만 wxPython에 대한 지식이 필요하지 않음) https://pypi.python.org/pypi/quickgui

원하는 수의 입력 (비율, 확인란, 입력 상자)을 만들고 단일 GUI에 자동 정렬 할 수 있습니다.


0

최근 메시지 상자 버전은 prompt_box 모듈입니다. 경고와 메시지의 두 가지 패키지가 있습니다. 메시지를 사용하면 상자를 더 잘 제어 할 수 있지만 입력하는 데 시간이 더 오래 걸립니다.

경고 코드 예 :

import prompt_box

prompt_box.alert('Hello') #This will output a dialog box with title Neutrino and the 
#text you inputted. The buttons will be Yes, No and Cancel

메시지 코드 예 :

import prompt_box

prompt_box.message('Hello', 'Neutrino', 'You pressed yes', 'You pressed no', 'You 
pressed cancel') #The first two are text and title, and the other three are what is 
#printed when you press a certain button

0

스레딩이있는 ctype 모듈

tkinter 메시지 상자를 사용하고 있었지만 코드가 충돌했습니다. 왜 그런지 알고 싶지 않았기 때문에 대신 ctypes 모듈을 사용했습니다.

예를 들면 :

import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

Arkelis 에서 코드를 받았습니다.


나는 코드가 충돌하지 않는 것이 마음에 들었으므로 작업하고 스레딩을 추가하여 코드가 실행되도록했습니다.

내 코드의 예

import ctypes
import threading


def MessageboxThread(buttonstyle, title, text, icon):
    threading.Thread(
        target=lambda: ctypes.windll.user32.MessageBoxW(buttonstyle, text, title, icon)
    ).start()

messagebox(0, "Your title", "Your text", 1)

버튼 스타일 및 아이콘 번호 :

## 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

0

pyautogui또는 pymsgbox다음을 사용할 수 있습니다 .

import pyautogui
pyautogui.alert("This is a message box",title="Hello World")

사용 pymsgbox은 다음을 사용하는 것과 동일합니다 pyautogui.

import pymsgbox
pymsgbox.alert("This is a message box",title="Hello World")
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.