Widgets
In this part of the Tkinter tutorial, we will cover some basic Tkinter widgets.Widgets are basic building blocks of a GUI application. Over the years, several widgets became a standard in all toolkits on all OS platforms. For example a button, a check box or a scroll bar. Some of them might have a different name. For instance, a check box is called a check button in Tkinter. Tkinter has a small set of widgets which cover the basic programming needs. More specialized components can be created as custom widgets.
Checkbutton
TheCheckbutton
is a widget, that has two states. On and Off. The On state is visualized by a check mark. It is used to denote some boolean property. The Checkbutton
widget provides a check box with a text label. #!/usr/bin/pythonIn our example, we place a check button on the window. The check button shows/hides the title of the window.
# -*- coding: utf-8 -*-
"""
ZetCode Tkinter tutorial
This program toggles the title of the
window with the Checkbutton widget
author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""
from Tkinter import Tk, Frame, Checkbutton
from Tkinter import IntVar, BOTH
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Checkbutton")
self.pack(fill=BOTH, expand=1)
self.var = IntVar()
cb = Checkbutton(self, text="Show title",
variable=self.var, command=self.onClick)
cb.select()
cb.place(x=50, y=50)
def onClick(self):
if self.var.get() == 1:
self.master.title("Checkbutton")
else:
self.master.title("")
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
self.var = IntVar()We create an
IntVar
object. It is a value holder for integer values for widgets in Tkinter. cb = Checkbutton(self, text="Show title",An instance of the
variable=self.var, command=self.onClick)
Checkbutton
is created. The value holder is connected to the widget via the variable
parameter. When we click on the check button, the onClick() method is called. This is done with the command
parameter. cb.select()Initially, the title is shown in the titlebar. So at the start, we make it checked with the
select()
method. if self.var.get() == 1:Inside the onClick() method, we display or hide the title based on the value from the self.var variable.
self.master.title("Checkbutton")
else:
self.master.title("")
Figure: Checkbutton
Label
TheLabel
widget is used to display text or images. No user interaction is available. sudo apt-get install python-imaging-tkIn order to run this example, we must install python-imaging-tk module.
#!/usr/bin/pythonOur example shows an image on the window.
# -*- coding: utf-8 -*-
"""
ZetCode Tkinter tutorial
In this script, we use the Label
widget to show an image.
author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""
from PIL import Image, ImageTk
from Tkinter import Tk, Frame, Label
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Label")
self.img = Image.open("tatras.jpg")
tatras = ImageTk.PhotoImage(self.img)
label = Label(self, image=tatras)
label.image = tatras
label.pack()
self.pack()
def setGeometry(self):
w, h = self.img.size
self.parent.geometry(("%dx%d+300+300") % (w, h))
def main():
root = Tk()
ex = Example(root)
ex.setGeometry()
root.mainloop()
if __name__ == '__main__':
main()
from PIL import Image, ImageTkBy default, the
Label
widget can display only a limited set of image types. To display a jpg image, we must use the PIL, Python Imaging Library module. self.img = Image.open("tatras.jpg")We create an image from the image file in the current working directory. Later we create a photo image from the image.
tatras = ImageTk.PhotoImage(self.img)
label = Label(self, image=tatras)The photoimage is given to the
image
parameter of the label widget. label.image = tatrasIn order not to be garbage collected, the image reference must be stored.
w, h = self.img.sizeWe make the size of the window to exactly fit the image size.
self.parent.geometry(("%dx%d+300+300") % (w, h))
Scale
Scale
is a widget that lets the user graphically select a value by sliding a knob within a bounded interval. Our example will show a selected number in a label widget. #!/usr/bin/pythonWe have two widgets in the above script. A scale and a label. A value from the scale widget is shown in the label widget.
# -*- coding: utf-8 -*-
"""
ZetCode Tkinter tutorial
In this script, we show how to
use the Scale widget.
author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""
from ttk import Frame, Label, Scale, Style
from Tkinter import Tk, BOTH, IntVar
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Scale")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
scale = Scale(self, from_=0, to=100,
command=self.onScale)
scale.place(x=20, y=20)
self.var = IntVar()
self.label = Label(self, text=0, textvariable=self.var)
self.label.place(x=130, y=70)
def onScale(self, val):
v = int(float(val))
self.var.set(v)
def main():
root = Tk()
ex = Example(root)
root.geometry("300x150+300+300")
root.mainloop()
if __name__ == '__main__':
main()
scale = Scale(self, from_=0, to=100,
command=self.onScale)
Scale
widget is created. We provide the lower and upper bounds. The from is a regular Python keyword, that is why there is an underscore after the first parameter. When we move the knob of the scale, the onScale() method is called. self.var = IntVar()An integer value holder and label widget are created. Value from the holder is shown in the label widget.
self.label = Label(self, text=0, textvariable=self.var)
def onScale(self, val):The onScale() method receives a currently selected value from the scale widget as a parameter. The value is first converted to a float and then to integer. Finally, the value is set to the value holder of the label widget.
v = int(float(val))
self.var.set(v)
Figure: Scale
Listbox
Listbox
is a widget that displays a list of objects. It allows the user to select one or more items. #!/usr/bin/pythonIn our example, we show a list of actresses in the
# -*- coding: utf-8 -*-
"""
ZetCode Tkinter tutorial
In this script, we show how to
use the Listbox widget.
author: Jan Bodar
last modified: December 2010
website: www.zetcode.com
"""
from ttk import Frame, Label, Style
from Tkinter import Tk, BOTH, Listbox, StringVar, END
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Listbox")
self.pack(fill=BOTH, expand=1)
acts = ['Scarlett Johansson', 'Rachel Weiss',
'Natalie Portman', 'Jessica Alba']
lb = Listbox(self)
for i in acts:
lb.insert(END, i)
lb.bind("<<ListboxSelect>>", self.onSelect)
lb.place(x=20, y=20)
self.var = StringVar()
self.label = Label(self, text=0, textvariable=self.var)
self.label.place(x=20, y=210)
def onSelect(self, val):
sender = val.widget
idx = sender.curselection()
value = sender.get(idx)
self.var.set(value)
def main():
root = Tk()
ex = Example(root)
root.geometry("300x250+300+300")
root.mainloop()
if __name__ == '__main__':
main()
Listbox
. The currently selected actress is displayed in a label widget. acts = ['Scarlett Johansson', 'Rachel Weiss',This is a list of actresses to be shown in the listbox.
'Natalie Portman', 'Jessica Alba']
lb = Listbox(self)We create an instance of the
for i in acts:
lb.insert(END, i)
Listbox
and insert all the items from the above mentioned list. lb.bind("<<ListboxSelect>>", self.onSelect)When we select an item in the listbox, the <<ListboxSelect>> event is generated. We bind the onSelect() method to this event.
self.var = StringVar()A label and its value holder is created. In this label we will display the currently selected item.
self.label = Label(self, text=0, textvariable=self.var)
sender = val.widgetWe get the sender of the event. It is our listbox widget.
idx = sender.curselection()We find out the index of the selected item using the
curselection()
method. value = sender.get(idx)The actual value is retrieved with the
get()
method, which takes the index of the item. self.var.set(value)Finally, the label is updated.
Figure: Listbox widget
In this part of the Tkinter tutorial, we have presented several Tkinter widgets.
No comments:
Post a Comment