0% found this document useful (0 votes)
60 views

Message Widget in Tkinter: W Message (Master, Option, ... )

The widget can be used to display short text messages over multiple lines. While it is similar to the Label widget, the Message widget allows changing font within the widget. It provides automatic line breaks and justification of multiline text. Radio buttons allow a single selection from a predefined set of options and are grouped by a common variable that changes based on selection. Checkboxes allow multiple selections from options and have boolean on/off states represented by variables. Menus provide lists of commands organized into categories that can execute functions when selected.

Uploaded by

ANKUR CHOUDHARY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Message Widget in Tkinter: W Message (Master, Option, ... )

The widget can be used to display short text messages over multiple lines. While it is similar to the Label widget, the Message widget allows changing font within the widget. It provides automatic line breaks and justification of multiline text. Radio buttons allow a single selection from a predefined set of options and are grouped by a common variable that changes based on selection. Checkboxes allow multiple selections from options and have boolean on/off states represented by variables. Menus provide lists of commands organized into categories that can execute functions when selected.

Uploaded by

ANKUR CHOUDHARY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Message widget in Tkinter

The widget can be used to display short text messages. The message widget
is similar in its functionality to the Label widget, but it is more flexible in
displaying text, e.g. the font can be changed while the Label widget can only
display text in a single font. It provides a multiline object, that is the text may
span more than one line. The text is automatically broken into lines and
justified. We were ambiguous, when we said, that the font of the message
widget can be changed. This means that we can choose arbitrarily a font for
one widget, but the text of this widget will be rendered solely in this font. This
means that we can't change the font within a widget. So it's not possible to
have a text in more than one font. If you need to display text in multiple fonts,
we suggest to use a Text widget. The syntax of a message widget:

w = Message ( master, option, ... )

Let's have a look at a simple example. The following script creates a message
with a famous saying by Mahatma Gandhi:

Import tkinter as tk
master = tk.Tk()
whatever_you_do = "Whatever you do will be
insignificant, but it is very important that you do
it.\n(Mahatma Gandhi)"
msg = tk.Message(master, text = whatever_you_do)
msg.config(bg='lightgreen', font=('times', 24,
'italic'))
msg.pack()
tk.mainloop()

The widget created by the script above looks like this:


Variable Classes in Tkinter
Some widgets (like text entry widgets, radio buttons and so on) can be
connected directly to application variables by using special options: variable,
textvariable, onvalue, offvalue, and value. This connection works both ways: if
the variable changes for any reason, the widget it's connected to will be
updated to reflect the new value. These Tkinter control variables are used like
regular Python variables to keep certain values.

It's not possible to hand over a regular Python variable to a widget through a
variable or textvariable option. The only kinds of variables for which this works
are variables that are subclassed from a class called Variable, defined in the
Tkinter module. They are declared like this:

 x = StringVar() # Holds a string; default value ""


 x = IntVar() # Holds an integer; default value 0
 x = DoubleVar() # Holds a float; default value 0.0
 x = BooleanVar() # Holds a boolean, returns 0 for False and 1 for True

To read the current value of such a variable, call the method get(). The value
of such a variable can be changed with the set() method.
Radio Buttons in Tkinter
A radio button, sometimes called option button, is a graphical user interface
element of Tkinter, which allows the user to choose (exactly) one of a
predefined set of options. Radio buttons can contain text or images. The
button can only display text in a single font. A Python function or method can
be associated with a radio button. This function or method will be called, if you
press this radio button.

Radio buttons are named after the physical buttons used on old radios to
select wave bands or preset radio stations. If such a button was pressed,
other buttons would pop out, leaving the pressed button the only pushed in
button.

Each group of Radio button widgets has to be associated with the same
variable. Pushing a button changes the value of this variable to a predefined
certain value.

Simple Example With Radio Buttons


Import tkinter as tk

root = tk.Tk()

v = tk.IntVar()

tk.Label(root,
text="""Choose a
programming language:""",
justify = tk.LEFT,
padx = 20).pack()

tk.Radiobutton(root,
text="Python",
padx = 20,
variable=v,
value=1).pack(anchor=tk.W)

tk.Radiobutton(root,
text="Perl",
padx = 20,
variable=v,
value=2).pack(anchor=tk.W)

root.mainloop()

The result of the previous example looks like this:

Improving the Example

In many cases, there are more than two radio buttons. It would be
cumbersome, if we have to define and write down each button. The solution is
shown in the following example. We have a list "languages", which contains
the button texts and the corresponding values. We can use a for loop to
create all the radio buttons. The list of tuples 'languages' containes both the
languages and the values, which will be assigned to the variable 'v', if the
corresponding language is clicked on.

Import tkinter as tk

root = tk.Tk()

v = tk.IntVar()
v.set(1) # initializing the choice, i.e. Python

languages = [("Python", 101),


("Perl", 102),
("Java", 103),
("C++", 104),
("C", 105)]

def ShowChoice():
print(v.get())

tk.Label(root,
text="""Choose your favourite
programming language:""",
justify = tk.LEFT,
padx = 20).pack()

for language, val in languages:


tk.Radiobutton(root,
text=language,
padx = 20,
variable=v,
command=ShowChoice,
value=val).pack(anchor=tk.W)

root.mainloop()

The result of the previous example looks like this:

Checkboxes in Tkinter
Checkboxes, also known as tickboxes or tick boxes or check boxes, are
widgets that permit the user to make multiple selections from a number of
different options. This is different to a radio button, where the user can make
only one choice.
Usually, checkboxes are shown on the screen as square boxes that can
contain white spaces (for false, i.e not checked) or a tick mark or X (for true,
i.e. checked).

A caption describing the meaning of the checkbox is usually shown adjacent


to the checkbox. The state of a checkbox is changed by clicking the mouse on
the box. Alternatively it can be done by clicking on the caption, or by using a
keyboard shortcut, for example, the space bar.

A Checkbox has two states: on or off.

The TkinterCheckbutton widget can contain text, but only in a single font, or
images, and a button can be associated with a Python function or method.
When a button is pressed, Tkinter calls the associated function or method.
The text of a button can span more than one line.

Simple Example

The following example presents two checkboxes "male" and "female". Each
checkbox needs a different variable name (IntVar()).

From tkinter import *


master = Tk()
var1 = IntVar()
Checkbutton(master, text="male",
variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text="female",
variable=var2).grid(row=1, sticky=W)
mainloop()

If we start this script, we get the following window:


We can improve this example a little bit. First we add a Label to it.
Furthermore we add two Buttons, one to leave the application and the other
one to view the values var1 and var2.

From tkinter import *


master = Tk()

def var_states():
print("male: %d,\nfemale: %d" % (var1.get(),
var2.get()))

Label(master, text="Your sex:").grid(row=0, sticky=W)


var1 = IntVar()
Checkbutton(master, text="male",
variable=var1).grid(row=1, sticky=W)
var2 = IntVar()
Checkbutton(master, text="female",
variable=var2).grid(row=2, sticky=W)
Button(master, text='Quit',
command=master.quit).grid(row=3, sticky=W, pady=4)
Button(master, text='Show',
command=var_states).grid(row=4, sticky=W, pady=4)
mainloop()

The result of the previous script looks like this:

If we check "male" and click on "Show", we get the following output:


male: 1,
female: 0

Menus in Tkinter
Most people, if confronted with the word "menu", will immediately think of a
menu in a restaurant. Even though the menu of a restaurant and the menu of
a computer program have at first glance nothing in common, we can see that
yet the have a lot in common. In a restaurant, a menu is a presentation of all
their food and beverage offerings, while in a computer application it presents
all the commands and functions of the application, which are available to the
user via the grafical user interface.

Menus in GUIs are presented with a combination of text and symbols to


represent the choices. Selecting with the mouse (or finger on touch screens)
on one of the symbols or text, an action will be started. Such an action or
operation can, for example, be the opening or saving of a file, or the quitting or
exiting of an application.

A context menu is a menu in which the choices presented to the user are
modified according to the current context in which the user is located.

We introduce in this chapter of our Python Tkinter tutorial the pull-down


menus of Tkinter, i.e. the lists at the top of the windows, which appear (or pull
down), if you click on an item like, for example "File", "Edit" or "Help".
A Simple Menu Example
The following Python script creates a simple application window with menus.

From tkinter import *


From tkinter.filedialog import askopenfilename

def NewFile():
print("New File!")
def OpenFile():
name = askopenfilename()
print(name)
def About():
print("This is a simple example of a menu")

root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=NewFile)
filemenu.add_command(label="Open...",
command=OpenFile)
filemenu.add_separator()
filemenu.add_command(label="Exit",
command=root.quit)

helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...",
command=About)

mainloop()

It looks like this, if started:


Python – Tkinter Listbox
The Listbox widget is used to display a list of items from which a user can select a number of
items.

Syntax
Here is the simple syntax to create this widget −
w = Listbox( master, option, ... )

Parameters
 master − This represents the parent window.
 options − Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.

From Tkinterimport*
Import tkMessageBox
Import Tkinter

top=Tk()

Lb1=Listbox(top)
Lb1.insert(1,"Python")
Lb1.insert(2,"Perl")
Lb1.insert(3,"C")
Lb1.insert(4,"PHP")
Lb1.insert(5,"JSP")
Lb1.insert(6,"Ruby")

Lb1.pack()
top.mainloop()

When the above code is executed, it produces the following result −

You might also like