Tk Dialogs

Site Navigation



 

Standard Messages and Dialogs are Easily Included

The Main Form has an area labeled "Standard Dialogs" that gives the option to include calls to the standard messages and dialog boxes. Standard messages include Information, Warning, and Error displays. Standard dialogs include Yes/No, OK/Cancel, Retry/Cancel, and generic question dialog pop-ups.

In addition to simple messages and dialogs, there are standard dialogs for "File Open", "File Save", and "Select Directory". There is also a "Color Chooser" and a built-in method for setting timers to schedule tasks.

Simple Messages

These are strictly convenience functions that allow a quick copy and paste implementation of whatever message box or standard dialog needs arise. The only reason to bother with these very simple wrapper functions is to quickly provide the required syntax and a few usage tips.

The images below illustrate the standard messages.

MS Windows Info MS Windows Warning MS Windows Error
Linux Info Linux Warning Linux Error

The following calls will bring up each of the above message boxes.

        self.ShowInfo('FYI...','Dogs Bark!')
        self.ShowWarning( title='Sky Warning', message='The Sky Is Falling.')
        self.ShowError('All Is Lost',"We're Toast Man!!!")

The following code is what tk_happy includes in the saved python file, in order to enable the above calls to message boxes. As you can see, they are simply wrappers around the tkMessageBox calls.

    # standard message dialogs... showinfo, showwarning, showerror
    def ShowInfo(self, title='Title', message='your message here.'):
        tkMessageBox.showinfo( title, message )
        return
    def ShowWarning(self, title='Title', message='your message here.'):
        tkMessageBox.showwarning( title, message )
        return
    def ShowError(self, title='Title', message='your message here.'):
        tkMessageBox.showerror( title, message )
        return

Simple Dialogs

Source code to simplify calling standard dialog boxes is also included. The source code below is included in the saved python file along with the above message boxes.

    # standard question dialogs...
    #     askquestion, askokcancel, askyesno, or askretrycancel
    # return True for OK, Yes, Retry, False for Cancel or No
    def AskYesNo(self, title='Title', message='your question here.'):
        return tkMessageBox.askyesno( title, message )
    def AskOK_Cancel(self, title='Title', message='your question here.'):
        return tkMessageBox.askokcancel( title, message )
    def AskRetryCancel(self, title='Title', message='your question here.'):
        return tkMessageBox.askretrycancel( title, message )

    # return "yes" for Yes, "no" for No
    def AskQuestion(self, title='Title', message='your question here.'):
        return tkMessageBox.askquestion( title, message )

As the comments indicate, the top three dialogs return True or False. The AskQuestion dialog returns a string variable containing "yes" or "no". The above dialogs are implemented with calls as follows.

        if self.AskYesNo( title='Tango?', message='Do You Tango?'):
            print "Let's Tango."
        else:
            print "Let's Eat."


        if self.AskQuestion(title='Eat?', message='Do You Eat?')=='yes':
            print "Let's Eat."
        else:
            print "Let's Tango."

MS Windows Yes/No MS Windows Question MS Windows Question

Color Chooser

Another convenience function call is the Color Chooser. The convenience wrapper is shown below along with a description of the return format (a color tuple and a web-type hex string).

    # returns a color tuple and a string representation of the selected color
    def AskForColor(self,title='Pick Color'):
        ctuple,cstr = tkColorChooser.askcolor(title=title)
        return ctuple,cstr

The color chooser can be called as follows.

        ctuple,cstr = self.AskForColor('What is you favorite color?')
        print 'Your favorite color is',str(cstr)
        print 'As a color tuple it is',ctuple
        tkMessageBox.showinfo( 'Favorite Color'
            , 'Your favorite color is '+cstr +'\nAKA... '+str(ctuple) )
MS Windows Color Message

This message box and the color chooser to the right are the result of the above call.

MS Windows Color Chooser Linux Color Chooser

File Open, File Save, and Directory Dialogs

Opening a file can be accomplished with code similar to that shown below. Because the standard dialog, tkFileDialog.askopenfile, returns a file object, the tk_happy wrapper, AskOpenFile, returns a file object as well.

    def File_Btn_Button_Click(self, event): #click method for component ID=4
        pass
        # >>>>>>insert any user code below this comment for section "compID=4"
        filetypes = [('Include File','*.inc'), ('Any File','*.*')]
        f = self.AskOpenFile(title='Choose File',\ 
            mode='r', initialdir='.', filetypes=filetypes)

        try:
            s = str( f )
            contents = f.read()
            f.close()
            self.ShowInfo('Opened File',\ 
                s+'\nGot contents of length='+str(len(contents)) )
        except:
            self.ShowError('File Error', 'Failed on file open')

This message box to the right and the file open dialog below, are the result of the above call.

MS Windows File Open Result
MS Windows File Open
Linux File Open

The wrapper function for "File Open" is shown below. Notice the warning about opening a file with mode="w". It is better to use the "SaveAs" dialog for saving files so that sufficient safeguards can be put into place to prevent losing data.

Notice also from the comments, that the string name of the opened file can be obtained as the file object property, "fileobj.name".

    # return an OPEN file type object OR None (opened using mode, 'r','rb','w','wb')
    # WARNING... opening file with mode 'w' or 'wb' will erase contents
    def AskOpenFile(self, title='Choose File', mode='rb', initialdir='.', filetypes=None):
        if filetypes==None:
            filetypes = [
                ('Text File','*.txt'),
                ('Data File','*.dat'),
                ('Output File','*.out'),
                ('Any File','*.*')]
        fileobj = tkFileDialog.askopenfile(parent=self.master,mode=mode,title=title,
            initialdir=initialdir, filetypes=filetypes)

        # if opened, then fileobj.name contains the name string
        return fileobj # <-- an opened file, or the value None

Getting the name of a file to be saved uses the standard dialog tkFileDialog.asksaveasfilename which is wrapped by tk_happy as AskSaveasFilename. The code below shows how to call AskSaveasFilename.

        filetypes = [('Include File','*.inc'), ('Any File','*.*')]
        fname = self.AskSaveasFilename('Save File', filetypes)
        self.ShowInfo('Save Filename', fname + \
            "\n  Don't forget to use\nimport os\nand associated safeguards")

This message box to the right and the file save dialog below, are the result of the above call.

MS Windows File Save
MS Windows File Save

The wrapper function for "File Save" is shown below. It is better to use this dialog for saving files than the "File Open" with mode="w" (from above) so that sufficient safeguards can be put into place. (i.e. a file opened with mode="w" will lose any data already in the file.)

    # return a string containing file name (the calling routine will need to open the file)
    def AskSaveasFilename(self, title='Save File', filetypes=None, initialfile=''):
        if filetypes==None:
            filetypes = [
                ('Text File','*.txt'),
                ('Data File','*.dat'),
                ('Output File','*.out'),
                ('Any File','*.*')]

        fileName = tkFileDialog.asksaveasfilename(parent=self.master,\
            filetypes=filetypes, initialfile=initialfile ,title=title)
        return fileName # <-- string

Timer/Alarm

Timer alarms can be set with a single call.

        self.SetAlarm(milliseconds=1000)

The above call sets a 1 second timer (1000 milliseconds) that activates the tk_happy-generated code below when the timer goes off. The message box to the right is the result of the code below. You might prefer to simply copy the line
     self.master.after( milliseconds, self.Alarm )
and modify it for your needs, however, the tk_happy boilerplate can simplify the task.

MS Windows Alarm Linux Alarm
    # alarm function is called after specified number of milliseconds
    def SetAlarm(self, milliseconds=1000):
        self.master.after( milliseconds, self.Alarm )
    def Alarm(self):
        pass

        # >>>>>>insert any user code below this comment for section "standard_alarm"
        self.ShowInfo(title='Alarm Called', message='When the alarm goes off\n'+\
            'Do you know what to do?')

It is easier to copy and paste existing code snippets, than it is to remember Tkinter syntax.

Colorized listings thanks to ASPN Recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442482 by Peter Krantz