python msg_box
转自:http://www.cnblogs.com/otfsenter/
# _*_ coding: utf-8 _*_
# @Time : 2017/3/27 17:39
# @Author : otfsenter
# @File : msg_box.py #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 sys
RUNNING_PYTHON_2 = sys.version_info[0] == 2
if RUNNING_PYTHON_2:
import Tkinter as tk
import ttk
else:
import tkinter as tk rootWindowPosition = '+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 = 12
MONOSPACE_FONT_SIZE = 9 #a little smaller, because it it more legible at a smaller size
TEXT_ENTRY_FONT_SIZE = 12 # a little larger makes it easier to see STANDARD_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 = None
choiceboxWidget = None
entryWidget = None
boxRoot = None
buttonsFrame = None def 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 line def _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.resizable(False, False)
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 __replyButtonText def __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('<Escape>', __cancelButtonEvent) def _bindArrows(widget, skipArrowKeys=False):
widget.bind('<Down>', _tabRight)
widget.bind('<Up>' , _tabLeft) if not skipArrowKeys:
widget.bind('<Right>',_tabRight)
widget.bind('<Left>' , _tabLeft) def _tabRight(event):
boxRoot.event_generate('<Tab>') def _tabLeft(event):
boxRoot.event_generate('<Shift-Tab>') 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 loop def __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('<Escape>', __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('<Return>', __enterboxGetText)
entryWidget.bind('<Escape>', __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 __enterboxText def __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()
python msg_box的更多相关文章
- python 调用exe程序
#!/usr/bin/python #-*- coding:utf-8 -*- import os, subprocess import tkMessageBox import msg_box def ...
- 【求教 探讨】python tkinter的messagebox
最近有一个要求,用python的tkinter制作一个messagebox,传入3个参数: title text timeout.用户可以点击“确定” 关闭窗口: 或者 等待几秒(timeout) ...
- Python中的多进程与多线程(一)
一.背景 最近在Azkaban的测试工作中,需要在测试环境下模拟线上的调度场景进行稳定性测试.故而重操python旧业,通过python编写脚本来构造类似线上的调度场景.在脚本编写过程中,碰到这样一个 ...
- Python高手之路【六】python基础之字符串格式化
Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...
- Python 小而美的函数
python提供了一些有趣且实用的函数,如any all zip,这些函数能够大幅简化我们得代码,可以更优雅的处理可迭代的对象,同时使用的时候也得注意一些情况 any any(iterable) ...
- JavaScript之父Brendan Eich,Clojure 创建者Rich Hickey,Python创建者Van Rossum等编程大牛对程序员的职业建议
软件开发是现时很火的职业.据美国劳动局发布的一项统计数据显示,从2014年至2024年,美国就业市场对开发人员的需求量将增长17%,而这个增长率比起所有职业的平均需求量高出了7%.很多人年轻人会选择编 ...
- 可爱的豆子——使用Beans思想让Python代码更易维护
title: 可爱的豆子--使用Beans思想让Python代码更易维护 toc: false comments: true date: 2016-06-19 21:43:33 tags: [Pyth ...
- 使用Python保存屏幕截图(不使用PIL)
起因 在极客学院讲授<使用Python编写远程控制程序>的课程中,涉及到查看被控制电脑屏幕截图的功能. 如果使用PIL,这个需求只需要三行代码: from PIL import Image ...
- Python编码记录
字节流和字符串 当使用Python定义一个字符串时,实际会存储一个字节串: "abc"--[97][98][99] python2.x默认会把所有的字符串当做ASCII码来对待,但 ...
随机推荐
- 【转】python文件打开方式详解——a、a+、r+、w+区别
原文地址:http://blog.csdn.net/ztf312/article/details/47259805 第一步 排除文件打开方式错误: r只读,r+读写,不创建 w新建只写,w+新建读写, ...
- java笔记之线程方式1启动线程
* 需求:我们要实现多线程的程序. * 如何实现呢? * 由于线程是依赖进程而存在的,所以我们应该先创建一个进程出来. * 而进程是由系统创建的,所以我们应该去调用系统功能创建一个进程. * ...
- jquery cloudzoom 3.0,magiczoom 放大镜插件 破解 移除版权信息
jquery Cloud Zoom一款放大镜插件.但是无奈 官方下载的始终有版权信息,因此想到如下方法去掉版权信息,测试可行! 官方网址:http://www.starplugins.com/clou ...
- HDU3949:XOR(高斯消元)(线性基)
传送门 题意 给出n个数,任意个数任意数异或构成一个集合,询问第k大个数 分析 这题需要用到线性基,下面是一些资料 1.高斯消元&线性基&Matirx_Tree定理 笔记 2.关于线性 ...
- 最小割树Gomory–Hu tree
fanhq666地址:http://fanhq666.blog.163.com/blog/static/8194342620113495335724/ wiki地址(证明):https://en.wi ...
- bzoj 1927 [Sdoi2010]星际竞速【最小费用最大流】
果然还是不会建图- 设\( i \)到\( j \)有通路,代价为\( w[i][j] \),瞬移到i代价为\( a[i] \),瞬移到i代价为\( a[j] \),逗号前是流量. 因为每个点只能经过 ...
- python安装教学
1.首先登陆到python的官方网站 1https://www.python.org/ 2.鼠标放在Download上,点击下面对应的型号,我的是Windows 3.点击Windows到此页面,点击3 ...
- Unix\Linux | 总结笔记 | 查看文件的方式
0 目录 vi cat head tail more less 1.vi vi编辑器的内置命令 有些内置命令使用键盘组合键即可完成,有些内置命令则需要以冒号“:”开头输入.常用内置命令如下: Ctrl ...
- hdu 1044 Collect More Jewels
题意: 一个n*m的迷宫,在t时刻后就会坍塌,问:在逃出来的前提下,能带出来多少价值的宝藏. 其中: ’*‘:代表墙壁: '.':代表道路: '@':代表起始位置: '<':代表出口: 'A'~ ...
- 洛谷 P2312 解方程
题目 首先,可以确定的是这题的做法就是暴力枚举x,然后去计算方程左边与右边是否相等. 但是noip的D2T3怎么会真的这么简单呢?卡常卡的真是熟练 你需要一些优化方法. 首先可以用秦九韶公式优化一下方 ...