This document provides an introduction and reference to Tkinter, a Python GUI toolkit. It begins with introductory examples and explanations of Tkinter classes and widgets. The remainder of the document consists of reference sections for each Tkinter widget and geometry manager, describing when to use them, common patterns, available methods and options.
( ** Python Certification Training: https://www.edureka.co/python ** )
This Edureka PPT on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.
( ** Python Certification Training: https://www.edureka.co/python ** )
This Edureka PPT on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.
This presentation educates you about Python - Multithreaded
Programming, Starting a New Thread, The Threading Module, Creating Thread Using Threading Module, Synchronizing Threads and Multithreaded Priority Queue.
For more topics stay tuned with Learnbay.
This presentation educates you about Python - GUI Programming(Tkinter), Tkinter Programming with syntaxe example, Tkinter Widgets with Operator & Description, Standard attributes.
For more topics stay tuned with learnbay.
The presentation introduces the reader to the principles of user interaction in Android applications. First, events are introduced, together with the related concepts of callbacks and event listeners. It follows a discussion on how to handle events in a declarative fashion via the XML layout file.
What is Multithreading In Python | Python Multithreading Tutorial | EdurekaEdureka!
YouTube Link: https://youtu.be/JnFfp81VbOs
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Multithreading in Python'' will help you understand the concept of threading in python. Below are the topics covered in this live PPT:
What is multitasking in Python?
Types of multitasking
What is a thread?
How to achieve multithreading in Python?
When to use multithreading?
How to create threads in Python?
Advantages of multithreading
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
This presentation educates you about Python - Multithreaded
Programming, Starting a New Thread, The Threading Module, Creating Thread Using Threading Module, Synchronizing Threads and Multithreaded Priority Queue.
For more topics stay tuned with Learnbay.
This presentation educates you about Python - GUI Programming(Tkinter), Tkinter Programming with syntaxe example, Tkinter Widgets with Operator & Description, Standard attributes.
For more topics stay tuned with learnbay.
The presentation introduces the reader to the principles of user interaction in Android applications. First, events are introduced, together with the related concepts of callbacks and event listeners. It follows a discussion on how to handle events in a declarative fashion via the XML layout file.
What is Multithreading In Python | Python Multithreading Tutorial | EdurekaEdureka!
YouTube Link: https://youtu.be/JnFfp81VbOs
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Multithreading in Python'' will help you understand the concept of threading in python. Below are the topics covered in this live PPT:
What is multitasking in Python?
Types of multitasking
What is a thread?
How to achieve multithreading in Python?
When to use multithreading?
How to create threads in Python?
Advantages of multithreading
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
2. Review Copy. Do not redistribute! 1999-12-01 22:15
Toolbars ......................................................................................................................... 26
Status Bars..................................................................................................................... 27
Table of Contents 9. Dialog Windows ................................................................................................................. 29
Grid Layouts .................................................................................................................. 34
Preface ....................................................................................................................i Validating Data.............................................................................................................. 36
I. Introducing Tkinter ............................................................................................2 II. Tkinter Reference............................................................................................ 37
1. What's Tkinter?......................................................................................................................1 10. The BitmapImage Class ................................................................................................... 38
2. Hello, Tkinter ....................................................................................................................... 2 When to use the BitmapImage Class ...........................................................................38
Running the Example ..................................................................................................... 2 Patterns.......................................................................................................................... 38
Details .............................................................................................................................. 2 Methods .........................................................................................................................38
3. Hello, Again .......................................................................................................................... 4 Options .......................................................................................................................... 38
Running the Example ..................................................................................................... 4 11. The Button Widget............................................................................................................40
Details .............................................................................................................................. 5 When to use the Button Widget ...................................................................................40
More on widget references ............................................................................................. 6 Patterns..........................................................................................................................40
More on widget names.................................................................................................... 6 Methods ......................................................................................................................... 41
4. Tkinter Classes ..................................................................................................................... 8 Helpers........................................................................................................................... 41
Widget classes .................................................................................................................8 Options .......................................................................................................................... 41
Mixins .............................................................................................................................. 9 12. The Canvas Widget ...........................................................................................................44
Implementation mixins ......................................................................................... 9 When to use the Canvas Widget................................................................................... 44
Geometry mixins .................................................................................................... 9 Concepts ........................................................................................................................44
Widget configuration management ...................................................................... 9 Items ..................................................................................................................... 44
5. Widget Configuration..........................................................................................................11 Coordinate Systems ............................................................................................. 45
Configuration Interface .................................................................................................11 Item Specifiers ..................................................................................................... 45
Backwards Compatibility...............................................................................................12 Printing ................................................................................................................. 46
6. Widget Styling .....................................................................................................................13 Patterns.......................................................................................................................... 46
Colors ..............................................................................................................................13 Methods .........................................................................................................................46
Color Names ..........................................................................................................13 Printing .................................................................................................................48
RGB Specifications................................................................................................13 Searching for Items.............................................................................................. 49
Fonts .............................................................................................................................. 14 Manipulating Tags ...............................................................................................50
Font descriptors ................................................................................................... 14 Special Methods for Text Items............................................................................51
Font names ............................................................................................................15 Scrolling.................................................................................................................51
System fonts ......................................................................................................... 16 Options .......................................................................................................................... 52
X Font Descriptors............................................................................................... 16 13. The Canvas Arc Item ........................................................................................................54
Text Formatting .............................................................................................................17 Methods ......................................................................................................................... 54
Borders ...........................................................................................................................17 Options .......................................................................................................................... 55
Relief ......................................................................................................................17 14. The Canvas Bitmap Item.................................................................................................. 57
Focus Highlights .................................................................................................. 18 Bitmaps.......................................................................................................................... 57
Cursors........................................................................................................................... 18 Methods ......................................................................................................................... 58
7. Events and Bindings........................................................................................................... 19 Options .......................................................................................................................... 58
Events ............................................................................................................................ 19 15. The Canvas Image Item.................................................................................................... 59
The Event Object...................................................................................................21 Methods ......................................................................................................................... 59
Instance and Class Bindings.................................................................................21 coords ................................................................................................................... 59
Protocols............................................................................................................... 23 itemconfigure ....................................................................................................... 59
Other Protocols .................................................................................................... 24 Options .......................................................................................................................... 59
8. Application Windows.........................................................................................................25 16. The Canvas Line Item....................................................................................................... 61
Base Windows ............................................................................................................... 25 Methods ......................................................................................................................... 61
Menus ............................................................................................................................ 25 Options .......................................................................................................................... 61
i ii
Copyright (c) 1999 by Fredrik Lundh
3. Review Copy. Do not redistribute! 1999-12-01 22:15
17. The Canvas Oval Item.......................................................................................................63 Manager Methods ................................................................................................ 87
Methods ......................................................................................................................... 63 Options .......................................................................................................................... 87
Options .......................................................................................................................... 63 28. The IntVar Class...............................................................................................................89
18. The Canvas Polygon Item ................................................................................................64 When to use the IntVar Class .......................................................................................89
Methods .........................................................................................................................64 Patterns..........................................................................................................................89
Options .......................................................................................................................... 64 Methods .........................................................................................................................89
19. The Canvas Rectangle Item.............................................................................................. 66 29. The Label Widget .............................................................................................................90
Methods .........................................................................................................................66 When to use the Label Widget......................................................................................90
Options .......................................................................................................................... 66 Patterns..........................................................................................................................90
20. The Canvas Text Item ...................................................................................................... 67 Methods ......................................................................................................................... 91
Methods ......................................................................................................................... 67 Options .......................................................................................................................... 91
Options .......................................................................................................................... 67 30. The Listbox Widget.......................................................................................................... 93
21. The Canvas Window Item ................................................................................................69 When to use the Listbox Widget .................................................................................. 93
Methods .........................................................................................................................69 Patterns.......................................................................................................................... 93
Options .......................................................................................................................... 69 Methods .........................................................................................................................96
22. The Checkbutton Widget ................................................................................................. 70 Selection Methods................................................................................................ 97
When to use the Checkbutton Widget ......................................................................... 70 Scrolling Methods ................................................................................................ 97
Patterns.......................................................................................................................... 70 Options ..........................................................................................................................98
Methods ..........................................................................................................................71 31. The Menu Widget ........................................................................................................... 100
Options ...........................................................................................................................71 When to use the Menu Widget ................................................................................... 100
23. The DoubleVar Class........................................................................................................ 75 Patterns........................................................................................................................ 100
When to use the DoubleVar Class ................................................................................ 75 Methods ....................................................................................................................... 102
Patterns.......................................................................................................................... 75 Displaying Menus .............................................................................................. 104
Methods ......................................................................................................................... 75 Options ........................................................................................................................ 104
24. The Entry Widget ............................................................................................................. 76 32. The Menubutton Widget ............................................................................................... 107
When to use the Entry Widget ..................................................................................... 76 When to use the Menubutton Widget........................................................................ 107
Concepts ........................................................................................................................ 76 Patterns........................................................................................................................ 107
Indexes.................................................................................................................. 76 Methods ....................................................................................................................... 107
Patterns.......................................................................................................................... 76 Options ........................................................................................................................ 107
Methods ......................................................................................................................... 77 33. The Message Widget ...................................................................................................... 108
Selection Methods................................................................................................ 77 When to use the Message Widget............................................................................... 108
Scrolling Methods ................................................................................................ 78 Patterns........................................................................................................................ 108
Options .......................................................................................................................... 78 Methods ....................................................................................................................... 108
25. The Font Class ..................................................................................................................80 Options ........................................................................................................................108
Patterns..........................................................................................................................80 34. The Pack Geometry Manager .........................................................................................110
Methods .........................................................................................................................80 When to use the Pack Manager ...................................................................................110
Functions .......................................................................................................................80 Patterns.........................................................................................................................110
Options .......................................................................................................................... 81 Methods ........................................................................................................................110
26. The Frame Widget ...........................................................................................................82 Widget Methods ..................................................................................................110
When to use the Frame Widget .................................................................................... 82 Manager Methods ...............................................................................................110
Patterns.......................................................................................................................... 82 Options ......................................................................................................................... 111
Methods .........................................................................................................................82 35. The PhotoImage Class.....................................................................................................112
Options .......................................................................................................................... 82 When to use the PhotoImage Class.............................................................................112
27. The Grid Geometry Manager...........................................................................................84 Patterns.........................................................................................................................112
When to use the Grid Manager ....................................................................................84 Methods ........................................................................................................................112
Patterns..........................................................................................................................84 Options .........................................................................................................................113
Methods .........................................................................................................................86 36. The Place Geometry Manager ........................................................................................115
Widget Methods ...................................................................................................86 When to use the Place Manager .................................................................................. 115
iii iv
Copyright (c) 1999 by Fredrik Lundh
4. Review Copy. Do not redistribute! 1999-12-01 22:15
Patterns......................................................................................................................... 115 tag_delete .................................................................................................. 142
Methods ........................................................................................................................116 tag_config.................................................................................................. 142
Options ......................................................................................................................... 117 tag_cget ..................................................................................................... 142
37. The Radiobutton Widget.................................................................................................118 tag_bind .................................................................................................... 142
When to use the Radiobutton Widget.........................................................................118 tag_unbind ................................................................................................ 142
Patterns.........................................................................................................................118 tag_names ................................................................................................. 142
Methods ........................................................................................................................119 tag_nextrange ........................................................................................... 143
Options ........................................................................................................................ 120 tag_prevrange ........................................................................................... 143
38. The Scale Widget............................................................................................................ 123 tag_lower................................................................................................... 143
When to use the Scale Widget .................................................................................... 123 tag_raise .................................................................................................... 143
Patterns........................................................................................................................ 123 tag_ranges ................................................................................................. 143
Methods ....................................................................................................................... 123 Methods for Selections ...................................................................................... 143
Options ........................................................................................................................ 123 Methods for Rendering...................................................................................... 144
39. The Scrollbar Widget ......................................................................................................125 bbox ........................................................................................................... 144
When to use the Scrollbar Widget...............................................................................125 dlineinfo..................................................................................................... 144
Patterns.........................................................................................................................125 Methods for Printing.......................................................................................... 144
Methods ....................................................................................................................... 126 Methods for Searching....................................................................................... 144
Options ........................................................................................................................ 126 search......................................................................................................... 144
40. The StringVar Class ....................................................................................................... 129 Methods for Scrolling ........................................................................................ 145
When to use the StringVar Class ................................................................................ 129 scan_mark, scan_dragto .......................................................................... 145
Patterns........................................................................................................................ 129 xview, yview............................................................................................... 145
Methods ....................................................................................................................... 129 xview, yview............................................................................................... 145
41. The Text Widget ............................................................................................................. 130 xview, yview............................................................................................... 145
When to use the Text Widget ..................................................................................... 130 yview_pickplace ........................................................................................ 146
Concepts ...................................................................................................................... 130 Options ........................................................................................................................ 146
Indexes................................................................................................................ 130 42. The Toplevel Widget ...................................................................................................... 149
Lines and columns .....................................................................................131 When to use the Toplevel Widget............................................................................... 149
Line endings ...............................................................................................131 Methods ....................................................................................................................... 149
Named indexes...........................................................................................131 Options ........................................................................................................................ 149
Coordinates ............................................................................................... 132 43. Basic Widget Methods .................................................................................................... 151
Embedded objects..................................................................................... 132 Configuration ............................................................................................................... 151
Expressions ............................................................................................... 132 config ................................................................................................................... 151
Marks .................................................................................................................. 132 config ................................................................................................................... 151
Tags..................................................................................................................... 133 cget.......................................................................................................................151
Patterns.........................................................................................................................135 keys ......................................................................................................................151
Methods ........................................................................................................................137 Event processing ..........................................................................................................152
Methods for Marks............................................................................................. 138 mainloop..............................................................................................................152
Methods for Embedded Windows..................................................................... 139 quit .......................................................................................................................152
Methods for Embedded Images ........................................................................ 140 update ..................................................................................................................152
image_create ............................................................................................. 140 update_idletasks .................................................................................................152
index ...........................................................................................................141 focus_set..............................................................................................................152
delete ..........................................................................................................141 focus_displayof ...................................................................................................152
image_cget .................................................................................................141 focus_force ..........................................................................................................152
image_config..............................................................................................141 focus_get .............................................................................................................152
image_names .............................................................................................141 focus_lastfor........................................................................................................152
Methods for Tags ................................................................................................141 tk_focusNext .......................................................................................................153
tag_add...................................................................................................... 142 tk_focusPrev........................................................................................................153
tag_remove................................................................................................ 142 grab_current .......................................................................................................153
v vi
Copyright (c) 1999 by Fredrik Lundh
6. Review Copy. Do not redistribute! 1999-12-01 22:15
iconmask............................................................................................................. 164
iconname ............................................................................................................ 164
iconposition........................................................................................................ 164
iconwindow ........................................................................................................ 164
Property Access Methods ........................................................................................... 164
client ................................................................................................................... 164
colormapwindows .............................................................................................. 164
command ............................................................................................................ 164
focusmodel ......................................................................................................... 165
frame................................................................................................................... 165
positionfrom....................................................................................................... 165
protocol............................................................................................................... 165
sizefrom .............................................................................................................. 165
Index .................................................................................................................. 166
ix
Copyright (c) 1999 by Fredrik Lundh
7. Review Copy. Do not redistribute! 1999-12-01 22:15
Preface
This is yet another snapshot of my continously growing Tkinter documentation.
I. Introducing Tkinter
If you like this book, you might be interested in hearing that O'Reilly & Associates The first few chapters in this book provide a brief introduction to Tkinter. After reading this,
(http://www.ora.com) will be publishing a Tkinter book (tentatively called Programming you should have a fair grasp of the Tkinter fundamentals.
Tkinter in Python) in a not too distant future. This book features lots of brand new material
written by yours truly, giving you a more thorough description of Tkinter (and many other
things) than you can find anywhere else.
</F>
(last update: Oct 05, 1999)
i
Copyright (c) 1999 by Fredrik Lundh
8. Review Copy. Do not redistribute! 1999-12-01 22:15
Chapter 1. What's Tkinter? Chapter 2. Hello, Tkinter
The Tkinter module (“Tk interface”) is the standard Python interface to the Tk GUI toolkit But enough talk. Time to look at some code instead.
from Scriptics (http://www.scriptics.com) (formerly developed by Sun Labs). As you know, every serious tutorial should start with a “hello world”-type example. In this
Both Tk and Tkinter are available on most Unix platforms, as well as on Windows and overview, we'll show you not only one such example, but two.
Macintosh systems. Starting with the 8.0 release, Tk offers native look and feel on all
First, let's look at a pretty minimal version:
platforms.
Tkinter consists of a number of modules. The Tk interface is located in a binary module named Example 2-1. Our First Tkinter Program
_tkinter (this was tkinter in earlier versions). This module contains the low-level interface to
# File: hello1.py
Tk, and should never be used directly by application programmers. It is usually a shared library
(or DLL), but might in some cases be statically linked with the Python interpreter. from Tkinter import *
In addition to the Tk interface module, Tkinter includes a number of Python modules. The two
most important modules are the Tkinter module itself, and a module called Tkconstants. The root = Tk()
former automatically imports the latter, so to use Tkinter, all you need to do is to import one
w = Label(root, text="Hello, world!")
module:
w.pack()
import Tkinter
root.mainloop()
Or, more often:
from Tkinter import *
Running the Example
To run the program, run the script as usual:
$ python hello1.py
The following window appears.
Figure 2-1. Running the program
To stop the program, just close the window.
Details
We start by importing the Tkinter module. It contains all classes, functions and other things
needed to work with the Tk toolkit. In most cases, you can simply import everything from
Tkinter into your module's namespace:
from Tkinter import *
1 2
Copyright (c) 1999 by Fredrik Lundh
9. Review Copy. Do not redistribute! 1999-12-01 22:15
Chapter 2. Hello, Tkinter
To initialize Tkinter, we have to create a Tk root widget. This is an ordinary window, with a title
bar and other decoration provided by your window manager. You should only create one root
widget for each program, and it must be created before any other widgets. Chapter 3. Hello, Again
root = Tk()
When you write larger programs, it is usually a good idea to wrap your code up in one or more
Next, we create a Label widget as a child to the root window: classes. The following example is adapted from the “hello world” program in Matt Conway's A
Tkinter Life Preserver (http://www.python.org/docs/tkinter).
w = Label(root, text="Hello, world!")
w.pack() Example 3-1. Our Second Tkinter Program
A Label widget can display either text or an icon or other image. In this case, we use the text # File: hello2.py
option to specify which text to display. Next, we call the pack method on this widget, which
from Tkinter import *
tells it to size itself to fit the given text, and make itself visible. But before this happens, we
have to enter the Tkinter event loop: class App:
root.mainloop()
def __init__(self, master):
The program will stay in the event loop until we close the window. The event loop doesn't only
frame = Frame(master)
handle events from the user (such as mouse clicks and key presses) or the windowing system
frame.pack()
(such as redraw events and window configuration messages), it also handle operations queued
by Tkinter itself. Among these operations are geometry management (queued by the pack self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
method) and display updates. This also means that the application window will not appear self.button.pack(side=LEFT)
before you enter the main loop.
self.hi_there = Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
print "hi there, everyone!"
root = Tk()
app = App(root)
root.mainloop()
Running the Example
When you run this example, the following window appears.
Figure 3-1. Running the sample program (using Tk 8.0 on a Windows 95 box)
If you click the right button, the text “hi there, everyone!” is printed to the console. If you click
the left button, the program stops.
3 4
Copyright (c) 1999 by Fredrik Lundh
10. Review Copy. Do not redistribute! 1999-12-01 22:15
Chapter 3. Hello, Again Chapter 3. Hello, Again
The last call is to the mainloop method on the root widget. It enters the Tk event loop, in which
Details the application will stay until the quit method is called (just click the QUIT button), or the
window is closed.
This sample application is written as a class. The constructor (the __init__ method) is called
with a parent widget (the master), to which it adds a number of child widgets. The constructor
starts by creating a Frame widget. A frame is a simple container, and is in this case only used to More on widget references
hold the other two widgets.
In the second example, the frame widget is stored in a local variable named frame, while the
class App: button widgets are stored in two instance attributes. Isn't there a serious problem hidden in
def __init__(self, master):
here: what happens when the __init__ function returns and the frame variable goes out of
scope?
frame = Frame(master)
frame.pack() Just relax; there's actually no need to keep a reference to the widget instance. Tkinter
automatically maintains a widget tree (via the master and children attributes of each widget
The frame instance is stored in a local variable called frame. After creating the widget, we instance), so a widget won't disappear when the application's last reference goes away; it must
immediately call the pack method to make the frame visible. be explicitly destroyed before this happens (using the destroy method). But if you wish to do
We then create two Button widgets, as children to the frame. something with the widget after it has been created, you better keep a reference to the widget
instance yourself.
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT) Note that if you don't need to keep a reference to a widget, it might be tempting to create and
pack it on a single line:
self.hi_there = Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT) Button(frame, text="Hello", command=self.hello).pack(side=LEFT)
This time, we pass a number of options to the constructor, as keyword arguments. The first Don't store the result from this operation; you'll only get disappointed when you try to use that
button is labelled “QUIT”, and is made red (fg is short for foreground). The second is labelled value (the pack method returns None). To be on the safe side, it might be better to always
“Hello”. Both buttons also take a command option. This option specifies a function, or (as in separate construction from packing:
this case) a bound method, which will be called when the button is clicked.
w = Button(frame, text="Hello", command=self.hello)
The button instances are stored in instance attributes. They are both packed, but this time with w.pack(side=LEFT)
the side=LEFT argument. This means that they will be placed as far left as possible in the
frame; the first button is placed at the frame's left edge, and the second is placed just to the
right of the first one (at the left edge of the remaining space in the frame, that is). By default,
More on widget names
widgets are packed relative to their parent (which is master for the frame widget, and the Another source of confusion, especially for those who have some experience of programming
frame itself for the buttons). If the side is not given, it defaults to TOP. Tk using Tcl, is Tkinter's notion of the widget name. In Tcl, you must explicitly name each
The “hello” button callback is given next. It simply prints a message to the console everytime widget. For example, the following Tcl command creates a Button named “ok”, as a child to a
the button is pressed: widget named “dialog” (which in turn is a child of the root window, “.”).
def say_hi(self): button .dialog.ok
print "hi there, everyone!"
The corresponding Tkinter call would look like:
Finally, we provide some script level code that creates a Tk root widget, and one instance of the
App class using the root widget as its parent: ok = Button(dialog)
root = Tk() However, in the Tkinter case, ok and dialog are references to widget instances, not the actual
names of the widgets. Since Tk itself needs the names, Tkinter automatically assigns a unique
app = App(root) name to each new widget. In the above case, the dialog name is probably something like
“.1428748,” and the button could be named “.1428748.1432920”. If you wish to get the full
root.mainloop() name of a Tkinter widget, simply use the str function on the widget instance:
>>> print str(ok)
.1428748.1432920
5 6
Copyright (c) 1999 by Fredrik Lundh
11. Review Copy. Do not redistribute! 1999-12-01 22:15
Chapter 3. Hello, Again
(if you print something, Python automatically uses the str function to find out what to print.
But obviously, an operation like “name = ok” won't do the that, so make sure always to
explicitly use str if you need the name). Chapter 4. Tkinter Classes
If you really need to specify the name of a widget, you can use the name option when you
create the widget. One (and most likely the only) reason for this is if you need to interface with
code written in Tcl.
Widget classes
In the following example, the resulting widget is named “.dialog.ok” (or, if you forgot to name Tkinter supports 15 core widgets:
the dialog, something like “.1428748.ok”):
Table 4-1. Tkinter Widget Classes
ok = Button(dialog, name="ok")
Widget Description
To avoid conflicts with Tkinter's naming scheme, don't use names which only contain digits.
Button A simple button, used to execute a command or other operation.
Also note that name is a “creation only” option; you cannot change the name once you've
created the widget. Canvas Structured graphics. This widget can be used to draw graphs and plots,
create graphics editors, and to implement custom widgets.
Checkbutton Represents a variable that can have two distinct values. Clicking the
button toggles between the values.
Entry A text entry field.
Frame A container widget. The frame can have a border and a background, and
is used to group other widgets when creating an application or dialog
layout.
Label Displays a text or an image.
Listbox Displays a list of alternatives. The listbox can be configured to get
radiobutton or checklist behavior.
Menu A menu pane. Used to implement pulldown and popup menus.
Menubutton A menubutton. Used to implement pulldown menus.
Message Display a text. Similar to the label widget, but can automatically wrap text
to a given width or aspect ratio.
Radiobutton Represents one value of a variable that can have one of many values.
Clicking the button sets the variable to that value, and clears all other
radiobuttons associated with the same variable.
Scale Allows you to set a numerical value by dragging a “slider”.
Scrollbar Standard scrollbars for use with canvas, entry, listbox, and text widgets.
Text Formatted text display. Allows you to display and edit text with various
styles and attributes. Also supports embedded images and windows.
Toplevel A container widget displayed as a separate, top-level window.
Also note that there's no widget class hierarchy in Tkinter; all widget classes are siblings in the
inheritance tree.
7 8
Copyright (c) 1999 by Fredrik Lundh
12. Review Copy. Do not redistribute! 1999-12-01 22:15
Chapter 4. Tkinter Classes Chapter 4. Tkinter Classes
All these widgets provide the Misc and geometry management methods, the configuration interface. The latter can be used to set and query individual options, and is explained in further
management methods, and additional methods defined by the widget itself. In addition, the detail in the next chapter.
Toplevel class also provides the window manager interface. This means that a typical widget
class provides some 150 methods.
Mixins
The Tkinter module provides classes corresponding to the various widget types in Tk, and a
number of mixin and other helper classes (a mixin is a class designed to be combined with
other classes using multiple inheritance). When you use Tkinter, you should never access the
mixin classes directly.
Implementation mixins
The Misc class is used as a mixin by the root window and widget classes. It provides a large
number of Tk and window related services, which are thus available for all Tkinter core
widgets. This is done by delegation; the widget simply forwards the request to the appropriate
internal object.
The Wm class is used as a mixin by the root window and Toplevel widget classes. It provides
window manager services, also by delegation.
Using delegation like this simplifies your application code: once you have a widget, you can
access all parts of Tkinter using methods on the widget instance.
Geometry mixins
The Grid, Pack, and Place classes are used as mixins by the widget classes. They provide access
to the various geometry managers, also via delegation.
Table 4-2. Geometry Mixins
Manager Description
Grid The grid geometry manager allows you to create table-like layouts, by
organizing the widgets in a 2-dimensional grid. To use this geometry
manager, use the grid method.
Pack The pack geometry manager lets you create a layout by “packing” the
widgets into a parent widget, by treating them as rectangular blocks
placed in a frame. To use this geometry manager for a widget, use the
pack method on that widget to set things up.
Place The place geometry manager lets you explicitly place a widget in a given
position. To use this geometry manager, use the place method.
Widget configuration management
The Widget class mixes the Misc class with the geometry mixins, and adds configuration
management through the cget and configure methods, as well as through a partial dictionary
9 10
Copyright (c) 1999 by Fredrik Lundh
13. Review Copy. Do not redistribute! 1999-12-01 22:15
Chapter 5. Widget Configuration
Backwards Compatibility
Chapter 5. Widget Configuration Keyword arguments were introduced in Python 1.3. Before that, options were passed to the
widget constructors and configure methods using ordinary Python dictionaries. The source
To control the appearance of a widget, you usually use options rather than method calls. code could then look something like this:
Typical options include text and color, size, command callbacks, etc. To deal with options, all
core widgets implement the same configuration interface: self.button = Button(frame, {"text": "QUIT", "fg": "red", "command": frame.quit})
self.button.pack({"side": LEFT})
Configuration Interface The keyword argument syntax is of course much more elegant, and less error prone. However,
for compatibility with existing code, Tkinter still supports the older syntax. You shouldn't use
widgetclass(master, option=value, ...) ⇒ widget this syntax in new programs, even if it might be tempting in some cases. For example, if you
Create an instance of this widget class, as a child to the given master, and using the given create a custom widget which needs to pass configuration options along to its parent class, you
options. All options have default values, so in the simplest case, you only have to specify may come up with something like:
the master. You can even leave that out if you really want; Tkinter then uses the most
def __init__(self, master, **kw):
recently created root window as master. Note that the name option can only be set when
Canvas.__init__(self, master, kw) # kw is a dictionary
the widget is created.
This works just fine with the current version of Tkinter, but it may not work with future
cget(option) ⇒ string
versions. A more general approach is to use the apply function:
Return the current value of an option. Both the option name, and the returned value, are
strings. To get the name option, use str(widget) instead. def __init__(self, master, **kw):
apply(Canvas.__init__, (self, master), kw)
configure(option=value, ...)
The apply function takes a function (an unbound method, in this case), a tuple with arguments
config(option=value, ...)
(which must include self since we're calling an unbound method), and optionally, a dictionary
Set one or more options (given as keyword arguments). which provides the keyword arguments.
Note that some options have names that are reserved words in Python (class, from, ...). To use
these as keyword arguments, simply append an underscore to the option name (class_, from_,
...). Note that you cannot set the name option using this method; it can only be set when the
widget is created.
For convenience, the widgets also implement a partial dictionary interface. The __setitem__
method maps to configure, while __getitem__ maps to cget. As a result, you can use the
following syntax to set and query options:
value = widget[option]
widget[option] = value
Note that each assignment results in one call to Tk. If you wish to change multiple options, it is
usually a better idea to change them with a single call to config or configure (personally, I
prefer to always change options in that fashion).
The following dictionary method also works for widgets:
keys() ⇒ list
Return a list of all options that can be set for this widget. The name option is not included
in this list (it cannot be queried or modified through the dictionary interface anyway, so
this doesn't really matter).
11 12
Copyright (c) 1999 by Fredrik Lundh
14. Review Copy. Do not redistribute! 1999-12-01 22:15
Chapter 6. Widget Styling
Tk also supports the forms “#RGB” and “#RRRRGGGGBBBB” to specify each value with 16 and
65536 levels, respectively.
Chapter 6. Widget Styling You can use the winfo_rgb widget method to translate a color string (either a name or an RGB
specification) to a 3-tuple:
All Tkinter standard widgets provide a basic set of “styling” options, which allow you to modify
things like colors, fonts, and other visual aspects of each widget. rgb = widget.winfo_rgb("red")
red, green, blue = rgb[0]/256, rgb[1]/256, rgb[2]/256
Colors Note that winfo_rgb returns 16-bit RGB values, ranging from 0 to 65535. To map them into the
more common 0-255 range, you must divide each value by 256 (or shift them 8 bits to the
Most widgets allow you to specify the widget and text colors, using the background and right).
foreground options. To specify a color, you can either use a color name, or explicitly specify the
red, green, and blue (RGB) color components.
Fonts
Color Names Widgets that allow you to display text in one way or another also allows you to specify which
Tkinter includes a color database which maps color names to the corresponding RGB values. font to use. All widgets provide reasonable default values, and you seldom have to specify the
This database includes common names like Red, Green, Blue, Yellow, and LightBlue, but also font for simpler elements like labels and buttons.
more exotic things like Moccasin, PeachPuff, etc. Fonts are usually specifed using the font widget option. Tkinter supports a number of different
On an X window system, the color names are defined by the X server. You might be able to font descriptor types:
locate a file named xrgb.txt which contains a list of color names and the corresponding RGB • Font descriptors
values. On Windows and Macintosh systems, the color name table is built into Tk.
• User-defined font names
Under Windows, you can also use the Windows system colors (these can be changed by the
• System fonts
user via the control panel):
SystemActiveBorder, SystemActiveCaption, SystemAppWorkspace, SystemBackground,
• X font descriptors
SystemButtonFace, SystemButtonHighlight, SystemButtonShadow, SystemButtonText, With Tk versions before 8.0, only X font descriptors are supported (see below).
SystemCaptionText, SystemDisabledText, SystemHighlight, SystemHighlightText,
SystemInactiveBorder, SystemInactiveCaption, SystemInactiveCaptionText, SystemMenu,
SystemMenuText, SystemScrollbar, SystemWindow, SystemWindowFrame, SystemWindowText.
Font descriptors
On the Macintosh, the following system colors are available: Starting with Tk 8.0, Tkinter supports platform independent font descriptors. You can specify a
font as tuple containing a family name, a height in points, and optionally a string with one or
SystemButtonFace, SystemButtonFrame, SystemButtonText, SystemHighlight,
SystemHighlightText, SystemMenu, SystemMenuActive, SystemMenuActiveText,
more styles. Examples:
SystemMenuDisabled, SystemMenuText, SystemWindowBody.
("Times", 10, "bold")
Color names are case insensitive. Many (but not all) color names are also available with or ("Helvetica", 10, "bold italic")
without spaces between the words. For example, “lightblue”, “light blue”, and “Light Blue” all ("Symbol", 8)
specify the same color.
To get the default size and style, you can give the font name as a single string. If the family
name doesn't include spaces, you can also add size and styles to the string itself:
RGB Specifications
"Times 10 bold"
If you need to explicitly specify a color, you can use a string with the following format:
"Helvetica 10 bold italic"
"Symbol 8"
#RRGGBB
Here are some families available on most Windows platforms:
RR, GG, BB are hexadecimal representations of the red, green and blue values, respectively.
The following sample shows how you can convert a color 3-tuple to a Tk color specification: Arial (corresponds to Helvetica), Courier New (Courier), Comic Sans MS, Fixedsys, MS Sans
Serif, MS Serif, Symbol, System, Times New Roman (Times), and Verdana:
tk_rgb = "#%02x%02x%02x" % (128, 192, 200)
13 14
Copyright (c) 1999 by Fredrik Lundh