Python tkinter.messagebox() Examples

The following are 30 code examples of tkinter.messagebox(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tkinter , or try the search function .
Example #1
Source File: gui_02.py    From Modern-Python-Standard-Library-Cookbook with MIT License 8 votes vote down vote up
def dialog(ask, title, message=None, **kwargs):
    for widget in (messagebox, simpledialog, filedialog):
        show = getattr(widget, 'ask{}'.format(ask), None)
        if show:
            break
    else:
        raise ValueError('Unsupported type of dialog: {}'.format(ask))

    options = dict(kwargs, title=title)
    for arg, replacement in dialog.argsmap.get(widget, {}).items():
        options[replacement] = locals()[arg]
    return show(**options) 
Example #2
Source File: gb_ide.py    From greenBerry with Apache License 2.0 7 votes vote down vote up
def wclose(self, event=0):
        if self.parent.title()[0] == "*":
            save = messagebox.askyesnocancel(
                "Save file",
                "You have unsaved changes.\nDo you want to save before closing?",
            )

            if save:
                self.save_file()
                if self.parent.title()[0] == "*":
                    self.wclose()
                else:
                    root.destroy()

            elif not save:
                root.destroy()
        else:
            root.destroy() 
Example #3
Source File: client-test2.py    From The-chat-room with MIT License 6 votes vote down vote up
def send(*args):
    # 没有添加的话发送信息时会提示没有聊天对象
    users.append('------Group chat-------')
    users.append('Robot')
    print(chat)
    if chat not in users:
        tkinter.messagebox.showerror('Send error', message='There is nobody to talk to!')
        return
    if chat == 'Robot':
        print('Robot')
    if chat == user:
        tkinter.messagebox.showerror('Send error', message='Cannot talk with yourself in private!')
        return
    mes = entry.get() + ':;' + user + ':;' + chat  # 添加聊天对象标记
    s.send(mes.encode())
    a.set('')  # 发送后清空文本框


# 创建发送按钮 
Example #4
Source File: viewer.py    From gdspy with Boost Software License 1.0 6 votes vote down vote up
def _properties(self, evt):
        if self.canvas.ruler is not None:
            self.canvas.delete(self.canvas.ruler)
            self.canvas.ruler = -1
        i = self.canvas.find_closest(
            self.canvas.canvasx(evt.x), self.canvas.canvasy(evt.y)
        )
        bb = self.canvas.bbox(i)
        if bb is not None:
            bb = (
                bb[0] * self.scale,
                -bb[3] * self.scale,
                bb[2] * self.scale,
                -bb[1] * self.scale,
            )
            tags = self.canvas.gettags(i)
            if "TEXT" not in tags:
                tkinter.messagebox.showinfo(
                    "Element information",
                    "Layer/datatpe: {0}\nVertices: {1}\nApproximate bounding box:\n({2[0]:g}, {2[1]:g}) - ({2[2]:g}, {2[3]:g})".format(
                        tags[0][1:], tags[1][1:], bb
                    ),
                    parent=self.canvas,
                ) 
Example #5
Source File: ttt_client_gui.py    From tic-tac-toe-in-python with MIT License 6 votes vote down vote up
def __start_client__(self):
		"""(Private) Starts the client side."""
		# Initialize the client object
		self.client = TTTClientGameGUI();
		# Gives the client a reference to self 
		self.client.canvas = self;
		try:
			# Get the host IP address
			host = socket.gethostbyname('s.CharmySoft.com');
		except:
			# If can't get the host IP from the domain
			tkinter.messagebox.showerror("Error", "Failed to get the game "+ 
				"host address from the web domain.\n" + 
				"Plase check your connection.");
			self.__on_return_clicked__();
			return;
		# Set the notif text
		self.set_notif_text("Connecting to the game server " + host + "...");
		# Connect to the server
		if(self.client.connect(host, "8080")):
			# If connected to the server
			# Start the game
			self.client.start_game();
			# Close the client
			self.client.close(); 
Example #6
Source File: PlayerView.py    From moviecatcher with MIT License 6 votes vote down vote up
def __getLoginInput (self, callback = '') :
		time.sleep(5)

		if self.browser.title == '百度网盘-全部文件' :
			cookies =  self.browser.get_cookies()
			cookieStr = ''
			for x in cookies :
				cookieStr += x['name'] + '=' + x['value'] + '; '

			result = {'stat': 1, 'msg': '获取成功'}
		else :
			result = {'stat': 2, 'msg': '获取失败'}

		self.browser.quit()

		if result['stat'] == 1 :
			self.slave.destroy()
			tkinter.messagebox.showinfo('Success', '登陆成功')
			callback(cookieStr)
		else :
			tkinter.messagebox.showinfo('Error', result['msg']) 
Example #7
Source File: MainView.py    From moviecatcher with MIT License 6 votes vote down vote up
def __mainWindow (self) :
		# master是TK框架的一个主线索,GUI的配置项都是从master着手
		self.master = tkinter.Tk()

		self.master.title(self.winTitle)
		self.master.resizable(width = 'false', height = 'false')
		if self.Tools.isWin() :  # 避免因为系统的原因导致获取不到图标
			self.master.iconbitmap(self.Tools.getRes('biticon.ico'))

		self.__topBox()  

		self.Cfg = Config.Config()
		if self.Cfg.connStat :
			menuBar = MenuBarView.GUI(self.master)
			menuBar.show()
		else :
			tkinter.messagebox.showinfo('Error', '创建配置文件失败。\r\n请检查「~/Library/Application Support」文件夹是否有操作权限!') 
Example #8
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def save_grammar(self, *args):
        filename = asksaveasfilename(filetypes=self.GRAMMAR_FILE_TYPES,
                                     defaultextension='.cfg')
        if not filename: return
        try:
            if filename.endswith('.pickle'):
                with open(filename, 'wb') as outfile:
                    pickle.dump((self._chart, self._tokens), outfile)
            else:
                with open(filename, 'w') as outfile:
                    prods = self._grammar.productions()
                    start = [p for p in prods if p.lhs() == self._grammar.start()]
                    rest = [p for p in prods if p.lhs() != self._grammar.start()]
                    for prod in start: outfile.write('%s\n' % prod)
                    for prod in rest: outfile.write('%s\n' % prod)
        except Exception as e:
            tkinter.messagebox.showerror('Error Saving Grammar',
                                   'Unable to open file: %r' % filename) 
Example #9
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def load_grammar(self, *args):
        "Load a grammar from a pickle file"
        filename = askopenfilename(filetypes=self.GRAMMAR_FILE_TYPES,
                                   defaultextension='.cfg')
        if not filename: return
        try:
            if filename.endswith('.pickle'):
                with open(filename, 'rb') as infile:
                    grammar = pickle.load(infile)
            else:
                with open(filename, 'r') as infile:
                    grammar = CFG.fromstring(infile.read())
            self.set_grammar(grammar)
        except Exception as e:
            tkinter.messagebox.showerror('Error Loading Grammar',
                                   'Unable to open file: %r' % filename) 
Example #10
Source File: client.py    From The-chat-room with MIT License 6 votes vote down vote up
def send(*args):
    # 没有添加的话发送信息时会提示没有聊天对象
    users.append('------Group chat-------')
    users.append('Robot')
    print(chat)
    if chat not in users:
        tkinter.messagebox.showerror('Send error', message='There is nobody to talk to!')
        return
    if chat == 'Robot':
        print('Robot')
    if chat == user:
        tkinter.messagebox.showerror('Send error', message='Cannot talk with yourself in private!')
        return
    mes = entry.get() + ':;' + user + ':;' + chat  # 添加聊天对象标记
    s.send(mes.encode())
    a.set('')  # 发送后清空文本框


# 创建发送按钮 
Example #11
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def load_chart(self, *args):
        "Load a chart from a pickle file"
        filename = askopenfilename(filetypes=self.CHART_FILE_TYPES,
                                   defaultextension='.pickle')
        if not filename: return
        try:
            with open(filename, 'rb') as infile:
                chart = pickle.load(infile)
            self._chart = chart
            self._cv.update(chart)
            if self._matrix: self._matrix.set_chart(chart)
            if self._matrix: self._matrix.deselect_cell()
            if self._results: self._results.set_chart(chart)
            self._cp.set_chart(chart)
        except Exception as e:
            raise
            tkinter.messagebox.showerror('Error Loading Chart',
                                   'Unable to open file: %r' % filename) 
Example #12
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def print_selection(self, *e):
        if self._root is None: return
        if self._selection is None:
            tkinter.messagebox.showerror('Print Error', 'No tree selected')
        else:
            c = self._cframe.canvas()
            for widget in self._treewidgets:
                if widget is not self._selection:
                    self._cframe.destroy_widget(widget)
            c.delete(self._selectbox)
            (x1,y1,x2,y2) = self._selection.bbox()
            self._selection.move(10-x1,10-y1)
            c['scrollregion'] = '0 0 %s %s' % (x2-x1+20, y2-y1+20)
            self._cframe.print_to_file()

            # Restore our state.
            self._treewidgets = [self._selection]
            self.clear()
            self.update() 
Example #13
Source File: run.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def show_socket_error(err, address):
    import tkinter
    import tkinter.messagebox as tkMessageBox
    root = tkinter.Tk()
    root.withdraw()
    if err.args[0] == 61: # connection refused
        msg = "IDLE's subprocess can't connect to %s:%d.  This may be due "\
              "to your personal firewall configuration.  It is safe to "\
              "allow this internal connection because no data is visible on "\
              "external ports." % address
        tkMessageBox.showerror("IDLE Subprocess Error", msg, parent=root)
    else:
        tkMessageBox.showerror("IDLE Subprocess Error",
                               "Socket Error: %s" % err.args[1], parent=root)
    root.destroy() 
Example #14
Source File: client.py    From The-chat-room with MIT License 5 votes vote down vote up
def login(*args):
    global IP, PORT, user
    IP, PORT = entryIP.get().split(':')  # 获取IP和端口号
    PORT = int(PORT)                     # 端口号需要为int类型
    user = entryUser.get()
    if not user:
        tkinter.messagebox.showerror('Name type error', message='Username Empty!')
    else:
        root1.destroy()                  # 关闭窗口 
Example #15
Source File: LoginUCASNetwork.py    From UCAS with GNU General Public License v3.0 5 votes vote down vote up
def askUserInfo():
    """弹窗让用户填写账号信息"""
    import tkinter
    import tkinter.messagebox
    tk = tkinter.Tk()

    userId, password = None, None
    tkinter.Label(tk, text='账号:').grid(row=0, column=0)
    txtUserId = tkinter.Entry(tk)
    txtUserId.grid(row=0, column=1)
    txtUserId.focus_set()

    tkinter.Label(tk, text='密码:').grid(row=1, column=0)
    txtPassword = tkinter.Entry(tk, show='*')
    txtPassword.grid(row=1, column=1)

    def btnOkClick():
        if not txtUserId.get() or not txtPassword.get():
            tkinter.messagebox.showerror('错误', '账号或密码不能为空!')
        else:
            nonlocal userId, password
            userId, password = txtUserId.get(), txtPassword.get()
            tk.destroy()

    tkinter.Button(tk, text="确定", command=btnOkClick).grid(row=2, column=1)
    tkinter.Button(tk, text="取消", command=tk.destroy).grid(row=2, column=0)

    tk.title('输入账号和密码')
    tk.attributes('-toolwindow', True)
    tk.resizable(False, False)
    tk.mainloop()
    return userId, password

# *************************** Helper End ****************************

# *************************** AuthInterface **************************** 
Example #16
Source File: cli.py    From stuntcat with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __tkinterbox(title, message):
    import tkinter, tkinter.messagebox
    tkinter.Tk().wm_withdraw()
    tkinter.messagebox.showerror(title, message) 
Example #17
Source File: run.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def show_socket_error(err, address):
    import tkinter
    import tkinter.messagebox as tkMessageBox
    root = tkinter.Tk()
    root.withdraw()
    if err.args[0] == 61: # connection refused
        msg = "IDLE's subprocess can't connect to %s:%d.  This may be due "\
              "to your personal firewall configuration.  It is safe to "\
              "allow this internal connection because no data is visible on "\
              "external ports." % address
        tkMessageBox.showerror("IDLE Subprocess Error", msg, parent=root)
    else:
        tkMessageBox.showerror("IDLE Subprocess Error",
                               "Socket Error: %s" % err.args[1], parent=root)
    root.destroy() 
Example #18
Source File: ResultView.py    From moviecatcher with MIT License 5 votes vote down vote up
def __taskDownload (self) :
		if self.resList.curselection() == () :
			tkinter.messagebox.showinfo('提示', '请选择一个文件进行操作!')
		else :
			idx = int(self.resList.curselection()[0])

			target = self.resRst[idx]

			Player = Play.Play(self.master)
			Player.dlLink(target) 
Example #19
Source File: run.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def show_socket_error(err, address):
    import tkinter
    import tkinter.messagebox as tkMessageBox
    root = tkinter.Tk()
    root.withdraw()
    if err.args[0] == 61: # connection refused
        msg = "IDLE's subprocess can't connect to %s:%d.  This may be due "\
              "to your personal firewall configuration.  It is safe to "\
              "allow this internal connection because no data is visible on "\
              "external ports." % address
        tkMessageBox.showerror("IDLE Subprocess Error", msg, parent=root)
    else:
        tkMessageBox.showerror("IDLE Subprocess Error",
                               "Socket Error: %s" % err.args[1], parent=root)
    root.destroy() 
Example #20
Source File: ttt_client_gui.py    From tic-tac-toe-in-python with MIT License 5 votes vote down vote up
def main():
	# Create a Tkinter object
	root = tkinter.Tk();
	# Set window title
	root.title("Tic Tac Toe");
	# Set window minimun size
	root.minsize(C_WINDOW_MIN_WIDTH, C_WINDOW_MIN_HEIGHT);
	# Set window size
	root.geometry(str(C_WINDOW_WIDTH) + "x" + str(C_WINDOW_HEIGHT));

	try:
		# Set window icon
		root.iconbitmap("res/icon.ico");
	except:	
		# An error has been caught when setting the icon
		# tkinter.messagebox.showerror("Error", "Can't set the window icon.");
		print("Can't set the window icon.");

	# Initialize the welcome scene
	welcome_scene = WelcomeScene(root);
	# Initialize the about scene
	about_scene = AboutScene(root);
	# Initialize the main game scene
	main_game_scene = MainGameScene(root);

	# Give a reference for switching between scenes
	welcome_scene.about_scene = about_scene;
	welcome_scene.main_game_scene = main_game_scene; 
	about_scene.welcome_scene = welcome_scene;
	main_game_scene.welcome_scene = welcome_scene;

	# Start showing the welcome scene
	welcome_scene.pack();
	    
	# Main loop
	root.mainloop(); 
Example #21
Source File: client-test.py    From The-chat-room with MIT License 5 votes vote down vote up
def login(*args):
    global IP, PORT, user
    IP, PORT = entryIP.get().split(':')  # 获取IP和端口号
    PORT = int(PORT)                     # 端口号需要为int类型
    user = entryUser.get()
    if not user:
        tkinter.messagebox.showerror('Name type error', message='Username Empty!')
    else:
        root1.destroy()                  # 关闭窗口 
Example #22
Source File: ttt_client_gui.py    From tic-tac-toe-in-python with MIT License 5 votes vote down vote up
def __init__(self, parent):
		"""Initializes the welcome scene."""

		# Initialize BaseScene
		super().__init__(parent);

		# Create a blue arch at the top of the canvas
		self.create_arc((-64, -368, C_WINDOW_WIDTH + 64, 192), 
			start=0, extent=-180, fill=C_COLOR_BLUE, outline="");

		try:
			# From the logo image file create a PhotoImage object 
			self.logo_image = tkinter.PhotoImage(file="res/icon.png");
			# Create the logo image at the center of the canvas
			logo = self.create_image((C_WINDOW_WIDTH/2, 
				C_WINDOW_HEIGHT/2 - 96), image=self.logo_image);
			# From the title image file create a PhotoImage object 
			self.title_image = tkinter.PhotoImage(file="res/title.png");
			# Create the logo image at the center of the canvas
			title = self.create_image((C_WINDOW_WIDTH/2, 
				C_WINDOW_HEIGHT/2 + 48), image=self.title_image);
		except:	
			# An error has been caught when creating the logo image
			tkinter.messagebox.showerror("Error", "Can't create images.\n" +
				"Please make sure the res folder is in the same directory" + 
				" as this script.");

		# Create the Play button
		play_btn = self.create_button(C_WINDOW_WIDTH/2, 
			C_WINDOW_HEIGHT/2 + 136, "Play");
		play_btn.command = self.__on_play_clicked__;
		# Create the About button
		about_btn = self.create_button(C_WINDOW_WIDTH/2, 
			C_WINDOW_HEIGHT/2 + 192, "About");
		about_btn.command = self.__on_about_clicked__;

		# Tag all of the drawn widgets for later reference
		self.addtag_all("all"); 
Example #23
Source File: client-test2.py    From The-chat-room with MIT License 5 votes vote down vote up
def login(*args):
    global IP, PORT, user
    IP, PORT = entryIP.get().split(':')  # 获取IP和端口号
    PORT = int(PORT)                     # 端口号需要为int类型
    user = entryUser.get()
    if not user:
        tkinter.messagebox.showerror('Name type error', message='Username Empty!')
    else:
        root1.destroy()                  # 关闭窗口 
Example #24
Source File: PlayerView.py    From moviecatcher with MIT License 5 votes vote down vote up
def showCloudLink (self) :
		if self.downLinkStat['err'] == 0 :
			if self.downLinkStat['msg'] == '' :
				self.timer = self.master.after(50, self.showCloudLink)
			else :
				window = tkinter.Toplevel()
				window.title('离线下载链接')
				window.resizable(width = 'false', height = 'false')
				if self.Tools.isWin() :
					window.iconbitmap(self.Tools.getRes('biticon.ico'))

				topZone = tkinter.Frame(window, bd = 0, bg="#444")
				topZone.pack(expand = True, fill = 'both')

				textZone = tkinter.Text(topZone, height = 8, width = 50, bd = 10, bg="#444", fg = '#ddd', highlightthickness = 0, selectbackground = '#116cd6')
				textZone.grid(row = 0, column = 0, sticky = '')
				textZone.insert('insert', self.downLinkStat['msg'])

				dlBtn = tkinter.Button(topZone, text = '下载', width = 10, fg = '#222', highlightbackground = '#444', command =  lambda url = self.downLinkStat['msg'] : webbrowser.open_new(url))
				dlBtn.grid(row = 1, column = 0, pady = 5)

		elif self.downLinkStat['err'] == 1 :
			tkinter.messagebox.showinfo('Error', '云端未能完成该任务,请等待云端下载完成or换个资源试试!')
		elif self.downLinkStat['err'] == 2 :
			tkinter.messagebox.showinfo('Notice', '磁力链接目前不支持离线下载,待后续版本更新。\r\n暂时请手动下载或上传链接至百度云!')
		elif self.downLinkStat['err'] == 3 :
			self.showAuthCode(self.downLinkStat['msg']) 
Example #25
Source File: PlayerView.py    From moviecatcher with MIT License 5 votes vote down vote up
def showWatchLink (self) :
		if self.watchLinkStat['err'] == 0 :
			if self.watchLinkStat['msg'] == '' :
				self.timer = self.master.after(50, self.showWatchLink)
			else :
				webbrowser.open_new(self.watchLinkStat['msg'])
		elif self.watchLinkStat['err'] == 1 :
			tkinter.messagebox.showinfo('Error', '云端未能完成该任务,请等待云端下载完成or换个资源试试!')
		elif self.watchLinkStat['err'] == 2 :
			tkinter.messagebox.showinfo('Notice', '磁力链接目前不支持在线观看,待后续版本更新。\r\n暂时请手动下载或上传链接至百度云!')
		elif self.watchLinkStat['err'] == 3 :
			self.showAuthCode(self.watchLinkStat['msg']) 
Example #26
Source File: gui_01.py    From Modern-Python-Standard-Library-Cookbook with MIT License 5 votes vote down vote up
def alert(title, message, kind='info', hidemain=True):
    if kind not in ('error', 'warning', 'info'):
        raise ValueError('Unsupported alert kind.')
    
    show_method = getattr(messagebox, 'show{}'.format(kind))
    show_method(title, message) 
Example #27
Source File: ResultView.py    From moviecatcher with MIT License 5 votes vote down vote up
def __taskWatch (self) :
		if self.resList.curselection() == () :
			tkinter.messagebox.showinfo('提示', '请选择一个文件进行操作!')
		else :
			idx = int(self.resList.curselection()[0])

			target = self.resRst[idx]

			Player = Play.Play(self.master)
			Player.watchLink(target) 
Example #28
Source File: ResultView.py    From moviecatcher with MIT License 5 votes vote down vote up
def __getChoose (self) :
		if self.resList.curselection() == () :
			tkinter.messagebox.showinfo('Notice', '请选择一个文件进行操作!')
		else :
			idx = int(self.resList.curselection()[0])

			target = self.resRst[idx] 
Example #29
Source File: MainView.py    From moviecatcher with MIT License 5 votes vote down vote up
def __topBox (self) :
		# TK框架里面的内容安排
		self.mainTop = tkinter.Frame(self.master, bd = 0, bg="#444")
		self.mainTop.pack(expand = True, fill = 'both', ipady = 5)

		self.searchKey = tkinter.Entry(
			self.mainTop, 
			width = 40, 
			bd = 0, 
			bg = "#222", 
			fg = "#ddd",
			highlightthickness = 1, 
			highlightcolor="#111", 
			highlightbackground = '#111', 
			selectbackground = '#116cd6', 
			justify='center'
		)
		self.searchKey.grid(row = 0, column = 1, padx = '10', pady = '20')
		self.searchKey.insert('end', '电影名/电视剧名')
		self.searchKey.bind('<FocusIn>', self.__cleanSearchKey)  # 事件监听绑定

		Searcher = Search.Search(self.master)  # 实例化search类
		self.sBtn = tkinter.Button(
			self.mainTop, 
			text = '搜索电影', 
			width = 10, 
			fg = '#222', 
			highlightbackground = '#444', 
			command = lambda key = self.searchKey : tkinter.messagebox.showinfo('Error', '请输入想要查询的电视剧/电影名再进行查询') if self.searchKey.get() == '电影名/电视剧名' or self.searchKey.get() == '' else Searcher.showResult(key)
		)
		self.sBtn.grid(row = 1, column = 1)

		self.mainTop.grid_columnconfigure(0, weight=1)
		self.mainTop.grid_columnconfigure(2, weight=1) 
Example #30
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def save_chart_dialog(self, *args):
        filename = asksaveasfilename(filetypes=self.CHART_FILE_TYPES,
                                     defaultextension='.pickle')
        if not filename: return
        try:
            with open(filename, 'wb') as outfile:
                pickle.dump(self._out_chart, outfile)
        except Exception as e:
            tkinter.messagebox.showerror('Error Saving Chart',
                                   'Unable to open file: %r\n%s' %
                                   (filename, e))