The python tkMessagebox for displaying output, errors, warnings and choice selections

Monday, May 25, 2009

This is perhaps the easiest python Tk widget to work with, the tkMessageBox which is used to display informational, error, warning and choice selection messages, however, this is a different module, though you can import widgets like Labels, Text, OptionMenu, Entry widgets from Tkinter, the tkMessagebox is another python module which creates a root Tkinter window and displays a dialogue box with the message type (say info, error, warnings, question and so on) with the message text.

Though this is a trivial code, but I want to keep a reference of it to know the different methods of tkMessageBox module which may be useful for GUI development in python, lets see the code.

1.  # File name:
2. # Author: S.Prasanna
4. from Tkinter import *
5. import tkMessageBox
7. if __name__ == "__main__":
9. root = Tk()
10. root.title("tkMessageBox Demo Widget")
11. root["padx"] = 20
12. root["pady"] = 20
14. tkinterLabel = Label(root)
15. tkinterLabel["text"] = "tkMessageBox demo running...."
16. tkinterLabel.pack()
18. tkMessageBox.showinfo(title="Tk Info box", \
19. message="This is a Tk Info/Message box used to display output")
21. tkMessageBox.showerror(title="Tk Error message box", \
22. message="This is a Tk Error Message box used to display errors")
24. tkMessageBox.showwarning(title="Tk Warning message box", \
25. message="This is a Tk Warning Message box used to display warnings")
27. if (tkMessageBox.askokcancel(title="Tk Ok/Cancel box", \
28. message="Select an option, OK or Cancel") == 1):
29. tkMessageBox.showinfo(title="Tk Ok/Cancel box", \
30. message="You selected OK option")
31. else:
32. tkMessageBox.showinfo(title="Tk Ok/Cancel box", \
33. message="You selected Cancel option")
35. if (tkMessageBox.askretrycancel(title="Tk Retry/Cancel box", \
36. message="Select an option, Retry or Cancel") == 1):
37. tkMessageBox.showinfo(title="Tk Retry/Cancel box", \
38. message="You selected Retry option")
39. else:
40. tkMessageBox.showinfo(title="Tk Retry/Cancel box", \
41. message="You selected Cancel option")
43. if (tkMessageBox.askyesno(title="Tk Yes/No box", \
44. message="Select an option, Yes or No") == 1):
45. tkMessageBox.showinfo(title="Tk Yes/No box", \
46. message="You selected Yes option")
47. else:
48. tkMessageBox.showinfo(title="Tk Yes/No box", \
49. message="You selected No option")
51. if (tkMessageBox.askquestion(title="Tk Question box", \
52. message="Is 1 + 1 = 2") == "yes"):
53. tkMessageBox.showinfo(title="Tk Question box", \
54. message="Correct Answer")
55. else:
56. tkMessageBox.showinfo(title="Tk Question box", \
57. message="Wrong Answer")
59. tkinterLabel["text"] = "tkMessageBox demo complete...."
61. root.mainloop()
Sample Output:

Figure 1: tkMessageBox Info, Ok/Cancel option displays


The code is quite simple and most part of it are self explanatory, however the askokcancel (line 27), askretrycancel (line 35) and askyesno (line 43) methods of tkMessageBox module displays choices to the end user and returns True(1) or False (0) depending on the user's selection, for the askyesno method, Yes choice returns a True value and a No choice returns False with a similar behavior for askretrycancel and askokcancel. There is a slight difference in the values returned by the tkMessageBox's askquestion method (line 51) which displays a couple of choices for the user (Yes and No) and returns yes/no respectively according to the user's selection.

The Tkinter OptionMenu widget and its usage

Saturday, May 23, 2009

The Tkinter OptionMenu is a GUI widget used to input multiple choice values, say selecting a date, month, year or age values, one can populate an OptionMenu intially with a tuple of option values and set a default value for the OptionMenu (Say a descriptive message "Select a Choice"), then once you select an option, you can get the selected option value through one of the OptionMenu properties or the OptionMenu control variable which is used to set the initial value.

We can create an OptionMenu widget through the python apply built-in method and initialize its keyword and non keyword arguments, in the below example we will see a simple OptionMenu with some option choices and when you click the Submit button, the selected option will be displayed when a valid choice is selected.

Listing 1:

1.  # File name:
2.  # Author: S.Prasanna
4.  from Tkinter import *
5.  import tkMessageBox
7.  def displayOption():
8.      """ Display the OptionMenu selection. """
10.     global optionMenuWidget, DEFAULTVALUE_OPTION
12.     if (optionMenuWidget.cget("text") == DEFAULTVALUE_OPTION):
13.         tkMessageBox.showerror("Tkinter OptionMenu Widget", "Select a valid option.")
14.     else:
15.         tkMessageBox.showinfo("Tkinter OptionMenu Widget", "OptionMenu value =" + optionMenuWidget.cget("text"))
17. if __name__ == "__main__":
19.     root = Tk()
20.     DEFAULTVALUE_OPTION = "Select an option."
22.     root.title("Tkinter OptionMenu Widget")
23.     root["padx"] = 40
24.     root["pady"] = 20 
26.     # Create an Option frame to hold the option Label and the optionMenu widget
27.     optionFrame = Frame(root)
29.     #Create a Label in textFrame
30.     optionLabel = Label(optionFrame)
31.     optionLabel["text"] = DEFAULTVALUE_OPTION
32.     optionLabel.pack(side=LEFT)
34.     # Create an optionMenu Widget in the optionFrame
35.     optionTuple = ("Option 1", "Option 2", "Option 3", "Option 4", "Option 5")
37.     defaultOption = StringVar()
38.     optionMenuWidget = apply(OptionMenu, (optionFrame, defaultOption) + optionTuple)
39.     defaultOption.set(DEFAULTVALUE_OPTION)
40.     optionMenuWidget["width"] = 15
41.     optionMenuWidget.pack(side=LEFT)
43.     optionFrame.pack()
45.     button = Button(root, text="Submit", command=displayOption)
46.     button.pack()
48.     root.mainloop()
Sample Output:

Figure 1: Tkinter OptionMenu


Though the above code uses an optionFrame (line 27), optionLabel (line 30) and an OptionMenu (line 38) which are wrapped inside the optionFrame, we will restrict our discussion only to the optionMenu.

The optionTuple (line 35) is a tuple with a different option choices, the defaultOption is a StringVar (line 37, a Tkinter String variable) which is used to set the initial value for OptionMenu and it will also hold the selected option choices. The apply function creates an OptionMenu widget with keyword and non-keyword parameters, its wrapped inside the optionFrame, associated with the defaultOption StringVar and initialized with the set of option values through the optionTuple.

The Submit button (line 45) invokes the displayOption (line 7) method when clicked, the displayOption menu fetches the OptionMenu selection choice through its method
When this value is equal to DEFAULTVALUE_OPTION (line 20) where the user didn't select an option, a Tkinter error message is flashed, else the OptionMenu selection choice is displayed, in the next blog, we will see more sophisticated OptionMenu methods including adding/removing options on the fly and fetching a reference to the OptionMenu control variable.

Python Tkinter Entry Widget: Restricting text input size

Sunday, May 17, 2009

In my last blog related to Python Tkinter programming, we have seen an example of a Tkinter Entry widget, which is a single line text input box, I was looking for a reasonable enhancement to that code, restricting the text input size, we have seen in many front end applications that this is a common practice, especially when you type details like your login user name, address, SSN and phone number which are finite length text inputs, so one should restrict those input size based on the maximum length that piece of information can have.

I was looking into different properties of Tkinter Entry text widget to see if there is a provision to set that condition, but then found that writing an event handler for the Entry text widget is the only way to do so, the event handler of a Tkinter widget binds a given event to that widget (say a mouse click, text input, mouse move, pressing Enter key, etc) and invokes a given method when that event is encountered, using the bind method of the Tkinter widget, one can easily add an event and associate it with the method to be called, lets see the code.

1.  # File name:
2. # Author: S.Prasanna
4. from Tkinter import *
5. import tkMessageBox
7. def validateTextInputSize(event):
8. """ Method to Validate Entry text input size """
12. if (event.widget.index(END) >= TEXT_MAXINPUTSIZE - 1):
13. event.widget.delete(TEXT_MAXINPUTSIZE - 1)
15. def displayText():
16. """ Display the Entry text value. """
18. global entryWidget
20. if entryWidget.get().strip() == "":
21. tkMessageBox.showerror("Tkinter Entry Widget", "Enter a text value")
22. else:
23. tkMessageBox.showinfo("Tkinter Entry Widget", "Text value =" + entryWidget.get().strip())
25. if __name__ == "__main__":
27. root = Tk()
30. root.title("Tkinter Entry Widget")
31. root["padx"] = 40
32. root["pady"] = 20
34. # Create a text frame to hold the text Label and the Entry widget
35. textFrame = Frame(root)
37. #Create a Label in textFrame
38. entryLabel = Label(textFrame)
39. entryLabel["text"] = "Enter the text:"
40. entryLabel.pack(side=LEFT)
42. # Create an Entry Widget in textFrame
43. entryWidget = Entry(textFrame)
44. entryWidget.bind("<Key>", validateTextInputSize)
45. entryWidget["width"] = 50
46. entryWidget.pack(side=LEFT)
48. textFrame.pack()
50. button = Button(root, text="Submit", command=displayText)
51. button.pack()
53. root.mainloop()
Sample Output:

Figure 1: Tkinter Entry Widget which restricts the input size to 20 characters


The code is quite simple, we create an Entry text widget (line 43) and bind a Key press event (line 44) which would call the validateTextInputSize method (line 10 - 13), which checks the maximum text input size and when that limit is reached, it will delete the text input corresponding to that index (TEXT_MAXINPUTSIZE = 20, line 8).

Sun Career Stimulus Package - Grow your career in Recession

Saturday, May 16, 2009

No, its not about money to stimulate your career, but its a Career Stimulus package from Sun with which you can grow your career in this tough economy by improving your skill sets, creating more opportunities and ultimately earn money. Sun has always been an innovative company and we care about developer community, students, universities, startups, eco-friendliness, open source and so on, this unique career stimulus program is designed to help you grow your career in this tough economy to get a competitive advantage with diverse skill sets on Sun technologies like Solaris and java to name a few.

Sun is always the one stop shop for world class open source software like OpenSolaris, Java, OpenOffice, Glassfish, XVM, etc, you will likely see that one or the other page or business sites you visit on a day would have been powered by a Sun technology, be it a hardware or software, therefore expertise in Sun technologies will always be beneficial for your career and I see lots of interest among some of my blog visitors who are keen to get more knowledge on Sun Certifications, notably the Sun Certified Solaris Associate (SCSA) and Sun Certified Java Programmer (SCJP), but they want to know more about the resources to get trained and prepare for those certifications.GetJava Download Button

Let me go through this Career Stimulus Package in detail.

1. Sun Career Stimulus Package

The Stimulus package web is designed to help you in everything, learning, getting certified, updating your resume with customized OpenOffice templates and making an illustrious career out of it, subscribe to it today to make the most out of it.

2. Sun Open Learning CenterInnovate on OpenSolaris

This is the home for you to get access to training materials for certifications, learning and getting hands on with Sun technologies, many people aspiring to become Sun Certified Professionals often mail me about the certification and training resources they need to get certified with Sun technologies, for them, please bookmark this page.

3. Sun Learning Media

The definitive resource for online learning, get access to presentations, white papers on different technologies, innovations and other learning media, this is not only limited to certifications, but above and beyond that, you can visit the most viewed, popular and recent articles, in short this is your technology playground if you are tech savvy.

4. Downloads Use

Last but not the least, I need to mention this, get your own copy of Netbeans IDE, OpenOffice, Java, OpenSolaris, Glassfish, MySQL, Desktop Virtualization software, JavaFX and so on for free, I am sure once you get these, you must be thinking of a startup of your own without any software license investments.

Hope this would give an overview of Sun's offerings and its upto you to get the best out of them, to conclude, Sun is not only the Dot in the Dot Com boom, but the Star of the Silcon Valley, the heart of the Internet, the second definition of open source and never sets.

Python Tkinter Entry Widget: A single line text input box

I was doing GUI programming in python for sometime now and its interesting, especially to learn creating different GUI widgets, exploring the numerous options, properties and methods of those widgets and so on, Tkinter seems to be an easy interface to work with, yes there are many GUI frameworks available for python like PyGTK, wxPython, etc but I wanted to work with the one bundled as part of python distribution to start with and hence Tkinter.

It was fun and I was thrilled to see the ease in which I can create a GUI applications with as few lines of code as possible, which I want to share and keep an online reference, to start with lets explore a simple Entry widget, which is a single line text box, I came to know about Tkinter Entry widget after working with Tkinter Text widget which can be used to input multiple lines of text, but I wanted to restrict the number of lines in the text box to one, after hitting the walls (writing event handlers to restrict the number of lines in the Text widget to one), I discovered the easiest way of doing it, an Entry widget which will do the job for you, so lets start with the simple one.

This program uses multiple widgets, buts lets focus our attention only to the Entry widget part, here we go.

Listing 1:

1.  # File name:
2. # Author: S.Prasanna
4. from Tkinter import *
5. import tkMessageBox
7. def displayText():
8. """ Display the Entry text value. """
10. global entryWidget
12. if entryWidget.get().strip() == "":
13. tkMessageBox.showerror("Tkinter Entry Widget", "Enter a text value")
14. else:
15. tkMessageBox.showinfo("Tkinter Entry Widget", "Text value =" + entryWidget.get().strip())
17. if __name__ == "__main__":
19. root = Tk()
21. root.title("Tkinter Entry Widget")
22. root["padx"] = 40
23. root["pady"] = 20
25. # Create a text frame to hold the text Label and the Entry widget
26. textFrame = Frame(root)
28. #Create a Label in textFrame
29. entryLabel = Label(textFrame)
30. entryLabel["text"] = "Enter the text:"
31. entryLabel.pack(side=LEFT)
33. # Create an Entry Widget in textFrame
34. entryWidget = Entry(textFrame)
35. entryWidget["width"] = 50
36. entryWidget.pack(side=LEFT)
38. textFrame.pack()
40. button = Button(root, text="Submit", command=displayText)
41. button.pack()
43. root.mainloop()

Sample Output:

Figure 1: Tkinter Entry Widget


For now we will focus only on the Entry widget part of the code, lines 33 - 36 creates an Entry widget inside a textFrame (line 26) and the Submit button (line 40), when clicked calls the displayText method (line 7) which uses the Entry widget's get method to fetch the text value of Entry widget (line 12), an error message is printed if no text is input (line 13) and the value of the text otherwise (line 15), in the next blog, we will improve the above code by restricting the text input size.

Copyright © 2016 Prasanna Seshadri,, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.