博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
tkinter custom message box
阅读量:6933 次
发布时间:2019-06-27

本文共 11506 字,大约阅读时间需要 38 分钟。

#coding:utf-8# PyMsgBox - A simple, cross-platform, pure Python module for JavaScript-like message boxes.# Al Sweigart al@inventwithpython.com# Modified BSD License# Derived from Stephen Raymond Ferg's EasyGui http://easygui.sourceforge.net/"""The four functions in PyMsgBox: - alert(text='', title='', button='OK')    Displays a simple message box with text and a single OK button. Returns the text of the button clicked on. - confirm(text='', title='', buttons=['OK', 'Cancel'])    Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on. - prompt(text='', title='' , default='')    Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked. - password(text='', title='', default='', mask='*')    Displays a message box with text input, and OK & Cancel buttons. Typed characters appear as *. Returns the text entered, or None if Cancel was clicked.""""""TODO Roadmap:- Be able to specify a custom icon in the message box.- Be able to place the message box at an arbitrary position (including on multi screen layouts)- Add mouse clicks to unit testing.- progress() function to display a progress bar- Maybe other types of dialog: open, save, file/folder picker, etc."""__version__ = '1.0.4'import sysRUNNING_PYTHON_2 = sys.version_info[0] == 2if RUNNING_PYTHON_2:    import Tkinter as tk    import ttkelse:    import tkinter as tkrootWindowPosition = '+150+100'if tk.TkVersion < 8.0 :    raise RuntimeError('You are running Tk version: ' + str(tk.TkVersion) + 'You must be using Tk version 8.0 or greater to use PyMsgBox.')# PROPORTIONAL_FONT_FAMILY = ('MS', 'Sans', 'Serif')PROPORTIONAL_FONT_FAMILY = '微软雅黑'MONOSPACE_FONT_FAMILY    = ('Courier')PROPORTIONAL_FONT_SIZE  = 12MONOSPACE_FONT_SIZE     =  9  #a little smaller, because it it more legible at a smaller sizeTEXT_ENTRY_FONT_SIZE    = 12  # a little larger makes it easier to seeSTANDARD_SELECTION_EVENTS = ['Return', 'Button-1', 'space']# Initialize some global variables that will be reset later__choiceboxMultipleSelect = None__widgetTexts = None__replyButtonText = None__choiceboxResults = None__firstWidget = None__enterboxText = None__enterboxDefaultText=''__multenterboxText = ''choiceboxChoices = NonechoiceboxWidget = NoneentryWidget = NoneboxRoot = NonebuttonsFrame = Nonedef alert(text='', title='', button='OK', root=None):    """Displays a simple message box with text and a single OK button. Returns the text of the button clicked on."""    return _buttonbox(msg=text, title=title, choices=[str(button)], root=root)def confirm(text='', title='', buttons=['OK', 'Cancel'], root=None):    """Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on."""    return _buttonbox(msg=text, title=title, choices=[str(b) for b in buttons], root=root)def prompt(text='', title='' , default='', root=None):    """Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked."""    return __fillablebox(text, title, default=default, mask=None,root=root)def password(text='', title='', default='', mask='*', root=None):    """Displays a message box with text input, and OK & Cancel buttons. Typed characters appear as *. Returns the text entered, or None if Cancel was clicked."""    return __fillablebox(text, title, default, mask=mask, root=root)import pymsgbox.native as native # This needs to be after the above functions so that the unimplmeneted native functions can default back to the above functions.native # dummy line just to make lint stop complaining about the previous linedef _buttonbox(msg, title, choices, root=None):    """    Display a msg, a title, and a set of buttons.    The buttons are defined by the members of the choices list.    Return the text of the button that the user selected.    @arg msg: the msg to be displayed.    @arg title: the window title    @arg choices: a list or tuple of the choices to be displayed    """    global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame    # Initialize __replyButtonText to the first choice.    # This is what will be used if the window is closed by the close button.    __replyButtonText = choices[0]    if root:        root.withdraw()        boxRoot = tk.Toplevel(master=root)        boxRoot.withdraw()    else:        boxRoot = tk.Tk()        boxRoot.withdraw()    boxRoot.title(title)    boxRoot.iconname('Dialog')    boxRoot.geometry(rootWindowPosition)    boxRoot.minsize(220, 120)    # ------------- define the messageFrame ---------------------------------    messageFrame = tk.Frame(master=boxRoot)    messageFrame.pack(side=tk.TOP, fill=tk.BOTH)    # ------------- define the buttonsFrame ---------------------------------    buttonsFrame = tk.Frame(master=boxRoot)    buttonsFrame.pack(side=tk.BOTTOM, fill=tk.BOTH, pady=20)    # -------------------- place the widgets in the frames -----------------------    messageWidget = tk.Message(messageFrame, text=msg, width=400)    messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY, PROPORTIONAL_FONT_SIZE))    messageWidget.pack(side=tk.TOP, expand=tk.YES, fill=tk.X, padx='3m', pady='3m')    __put_buttons_in_buttonframe(choices)    # -------------- the action begins -----------    # put the focus on the first button    __firstWidget.focus_force()    boxRoot.deiconify()    boxRoot.mainloop()    try:        boxRoot.destroy()    except tk.TclError:        __replyButtonText = 'Cancel'    if root: root.deiconify()    return __replyButtonTextdef __put_buttons_in_buttonframe(choices):    """Put the buttons in the buttons frame"""    global __widgetTexts, __firstWidget, buttonsFrame    __firstWidget = None    __widgetTexts = {}    i = 0    for buttonText in choices:        tempButton = ttk.Button(buttonsFrame, takefocus=1, text=buttonText)        _bindArrows(tempButton)        tempButton.pack(expand=tk.YES, side=tk.LEFT, padx='1m', pady='1m')                        # ipadx='2m', ipady='1m')        # remember the text associated with this widget        __widgetTexts[tempButton] = buttonText        # remember the first widget, so we can put the focus there        if i == 0:            __firstWidget = tempButton            i = 1        # for the commandButton, bind activation events to the activation event handler        commandButton  = tempButton        handler = __buttonEvent        for selectionEvent in STANDARD_SELECTION_EVENTS:            commandButton.bind('<%s>' % selectionEvent, handler)        if 'Cancel' in choices:            commandButton.bind('
', __cancelButtonEvent)def _bindArrows(widget, skipArrowKeys=False): widget.bind('
', _tabRight) widget.bind('
' , _tabLeft) if not skipArrowKeys: widget.bind('
',_tabRight) widget.bind('
' , _tabLeft)def _tabRight(event): boxRoot.event_generate('
')def _tabLeft(event): boxRoot.event_generate('
')def __buttonEvent(event): """ Handle an event that is generated by a person clicking a button. """ global boxRoot, __widgetTexts, __replyButtonText __replyButtonText = __widgetTexts[event.widget] boxRoot.quit() # quit the main loopdef __cancelButtonEvent(event): """Handle pressing Esc by clicking the Cancel button.""" global boxRoot, __widgetTexts, __replyButtonText __replyButtonText = 'Cancel' boxRoot.quit()def __fillablebox(msg, title='', default='', mask=None, root=None): """ Show a box in which a user can enter some text. You may optionally specify some default text, which will appear in the enterbox when it is displayed. Returns the text that the user entered, or None if he cancels the operation. """ global boxRoot, __enterboxText, __enterboxDefaultText global cancelButton, entryWidget, okButton if title == None: title == '' if default == None: default = '' __enterboxDefaultText = default __enterboxText = __enterboxDefaultText if root: root.withdraw() boxRoot = tk.Toplevel(master=root) boxRoot.withdraw() else: boxRoot = tk.Tk() boxRoot.withdraw() boxRoot.title(title) boxRoot.iconname('Dialog') boxRoot.geometry(rootWindowPosition) boxRoot.bind('
', __enterboxCancel) # ------------- define the messageFrame --------------------------------- messageFrame = tk.Frame(master=boxRoot) messageFrame.pack(side=tk.TOP, fill=tk.BOTH) # ------------- define the buttonsFrame --------------------------------- buttonsFrame = tk.Frame(master=boxRoot) buttonsFrame.pack(side=tk.TOP, fill=tk.BOTH) # ------------- define the entryFrame --------------------------------- entryFrame = tk.Frame(master=boxRoot) entryFrame.pack(side=tk.TOP, fill=tk.BOTH) # ------------- define the buttonsFrame --------------------------------- buttonsFrame = tk.Frame(master=boxRoot) buttonsFrame.pack(side=tk.TOP, fill=tk.BOTH) #-------------------- the msg widget ---------------------------- messageWidget = tk.Message(messageFrame, width='4.5i', text=msg) messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY, PROPORTIONAL_FONT_SIZE)) messageWidget.pack(side=tk.RIGHT, expand=1, fill=tk.BOTH, padx='3m', pady='3m') # --------- entryWidget ---------------------------------------------- entryWidget = tk.Entry(entryFrame, width=40) _bindArrows(entryWidget, skipArrowKeys=True) entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY, TEXT_ENTRY_FONT_SIZE)) if mask: entryWidget.configure(show=mask) entryWidget.pack(side=tk.LEFT, padx='3m') entryWidget.bind('
', __enterboxGetText) entryWidget.bind('
', __enterboxCancel) # put text into the entryWidget and have it pre-highlighted if __enterboxDefaultText != '': entryWidget.insert(0,__enterboxDefaultText) entryWidget.select_range(0, tk.END) # ------------------ ok button ------------------------------- okButton = tk.Button(buttonsFrame, takefocus=1, text='OK') _bindArrows(okButton) okButton.pack(expand=1, side=tk.LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m') # for the commandButton, bind activation events to the activation event handler commandButton = okButton handler = __enterboxGetText for selectionEvent in STANDARD_SELECTION_EVENTS: commandButton.bind('<%s>' % selectionEvent, handler) # ------------------ cancel button ------------------------------- cancelButton = tk.Button(buttonsFrame, takefocus=1, text='Cancel') _bindArrows(cancelButton) cancelButton.pack(expand=1, side=tk.RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m') # for the commandButton, bind activation events to the activation event handler commandButton = cancelButton handler = __enterboxCancel for selectionEvent in STANDARD_SELECTION_EVENTS: commandButton.bind('<%s>' % selectionEvent, handler) # ------------------- time for action! ----------------- entryWidget.focus_force() # put the focus on the entryWidget boxRoot.deiconify() boxRoot.mainloop() # run it! # -------- after the run has completed ---------------------------------- if root: root.deiconify() try: boxRoot.destroy() # button_click didn't destroy boxRoot, so we do it now except tk.TclError: return None return __enterboxTextdef __enterboxGetText(event): global __enterboxText __enterboxText = entryWidget.get() boxRoot.quit()def __enterboxRestore(event): global entryWidget entryWidget.delete(0,len(entryWidget.get())) entryWidget.insert(0, __enterboxDefaultText)def __enterboxCancel(event): global __enterboxText __enterboxText = None boxRoot.quit()

转载于:https://www.cnblogs.com/otfsenter/p/6626728.html

你可能感兴趣的文章
机器学习常见的几个误区--逻辑回归的变量之间如果线性相关
查看>>
批处理文件的@echo off是什么意思?
查看>>
Git 分布式版本管理
查看>>
[转]Display PDF within web browser using MVC3
查看>>
Angular - - ngHref、ngSrc、ngCopy/ngCut/ngPaste
查看>>
内存对齐的规则以及作用
查看>>
【c语言】模拟库函数strstr
查看>>
iOS开发-观察者模式
查看>>
JQuery实现一个简单的鼠标跟随提示效果
查看>>
jenkins 入门教程(下)
查看>>
Hello,Akka
查看>>
转图像偏微分方程不适定问题
查看>>
虚拟机内存结构划分
查看>>
Git忽略文件方法【转】
查看>>
Netron开发快速上手(一):GraphControl,Shape,Connector和Connection
查看>>
第九十六题(编写strcpy 函数)
查看>>
memcached单点故障与负载均衡
查看>>
poj3934Queue(dp)
查看>>
小小小女神啊~~~
查看>>
记得ajax中要带上AntiForgeryToken防止CSRF攻击
查看>>