(Ebook) Modern Tkinter for Busy Python Developers: Quickly learn to create great looking user interfaces for Windows, Mac and Linux using Python's standard GUI toolkit by Mark Roseman ISBN 9781999149567, 1999149564 instant download
(Ebook) Modern Tkinter for Busy Python Developers: Quickly learn to create great looking user interfaces for Windows, Mac and Linux using Python's standard GUI toolkit by Mark Roseman ISBN 9781999149567, 1999149564 instant download
https://ebooknice.com/product/modern-tkinter-for-busy-python-developers-
third-edition-37645540
https://ebooknice.com/product/python-gui-programming-cookbook-use-recipes-
to-develop-responsive-and-powerful-guis-using-tkinter-2nd-edition-29873630
(Ebook) Create GUI Applications with Python & Qt5: The hands-on
guide to making apps with Python by Martin Fitzpatrick
https://ebooknice.com/product/create-gui-applications-with-python-qt5-the-
hands-on-guide-to-making-apps-with-python-43766034
https://ebooknice.com/product/python-for-beginners-2018-edition-learn-to-
code-with-python-42932776
(Ebook) Create Gui Applications with Python & Qt5 by Martin
Fitzpack
https://ebooknice.com/product/create-gui-applications-with-python-
qt5-22683090
(Ebook) Create GUI Applications with Python & Qt6: The hands-on
guide to making apps with Python(pyside6 Edition) by Martin
Fitzpatrick
https://ebooknice.com/product/create-gui-applications-with-python-qt6-the-
hands-on-guide-to-making-apps-with-python-pyside6-edition-37263208
https://ebooknice.com/product/create-gui-applications-with-python-
qt5-pyside2-edition-11547142
https://ebooknice.com/product/python-unit-test-automation-practical-
techniques-for-python-developers-and-testers-50195020
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374
Modern Tkinter
for Busy Python Developers
Mark Roseman
1
Contents
Introduction..........................................................................................................................................7
Who this Tutorial is for....................................................................................................................7
Modern Best Practices.....................................................................................................................7
Tk Extensions..............................................................................................................................8
The Better Way Forward..................................................................................................................8
How to Use......................................................................................................................................9
Conventions................................................................................................................................9
Installing Tk........................................................................................................................................10
Installing Tk on Mac OS X............................................................................................................10
Install ActiveTcl........................................................................................................................10
Install Python............................................................................................................................10
Installing Tk on Windows..............................................................................................................11
Installing Tk on Linux...................................................................................................................12
Option 1. Your Linux Distribution's Package Manager............................................................12
Option 2. Install ActivePython..................................................................................................12
Option 3. Install Tcl/Tk and Compile the Standard Python Distribution..................................13
Verifying your Install................................................................................................................13
The Obligatory First Program........................................................................................................14
A First (Real) Example.......................................................................................................................14
Design............................................................................................................................................14
Code...............................................................................................................................................15
A Note on Coding Style............................................................................................................16
Step-by-Step Walkthrough.............................................................................................................17
What's Missing...............................................................................................................................19
Tk Concepts........................................................................................................................................19
Widgets..........................................................................................................................................19
Widget Classes..........................................................................................................................20
Window Hierarchy....................................................................................................................20
Creating and Using Widgets......................................................................................................21
Configuration Options...............................................................................................................21
Geometry Management..................................................................................................................22
The Problem..............................................................................................................................23
How it Works............................................................................................................................23
Event Handling..............................................................................................................................24
Command Callbacks.................................................................................................................24
Event Bindings..........................................................................................................................25
Virtual Events.......................................................................................................................25
Multiple Bindings.................................................................................................................26
Basic Widgets.....................................................................................................................................26
Frame.............................................................................................................................................26
Requested Size.....................................................................................................................27
Padding.................................................................................................................................27
Borders.................................................................................................................................27
Changing Styles....................................................................................................................28
Label..............................................................................................................................................28
Displaying Text....................................................................................................................29
Displaying Images................................................................................................................29
Layout...................................................................................................................................29
2
Fonts, Colors and More........................................................................................................30
Button.............................................................................................................................................31
Text or Image........................................................................................................................31
The Command Callback.......................................................................................................32
Button State..........................................................................................................................32
Checkbutton...................................................................................................................................33
Widget Value........................................................................................................................33
Radiobutton....................................................................................................................................34
Entry...............................................................................................................................................34
Passwords.............................................................................................................................35
Widget States........................................................................................................................35
Validation..............................................................................................................................36
Combobox......................................................................................................................................36
Predefined Values.................................................................................................................37
The Grid Geometry Manager.............................................................................................................37
Columns and Rows........................................................................................................................38
Spanning Multiple Cells................................................................................................................38
Layout within the Cell...................................................................................................................39
Handling Resize.............................................................................................................................40
Padding..........................................................................................................................................40
Additional Grid Features...............................................................................................................42
Querying and Changing Grid Options......................................................................................42
Internal Padding........................................................................................................................43
Forget and Remove...................................................................................................................43
Nested Layouts..........................................................................................................................44
More Widgets.....................................................................................................................................44
Listbox...........................................................................................................................................44
Populating the Listbox Items....................................................................................................45
Selecting Items..........................................................................................................................46
Stylizing the List.......................................................................................................................46
Keeping Extra Item Data...........................................................................................................46
Example....................................................................................................................................47
Scrollbar.........................................................................................................................................49
Example....................................................................................................................................51
SizeGrip.........................................................................................................................................51
Text................................................................................................................................................52
Contents....................................................................................................................................53
Progressbar.....................................................................................................................................53
Determinate Progess.................................................................................................................54
Indeterminate Progress..............................................................................................................54
Scale...............................................................................................................................................55
Spinbox..........................................................................................................................................56
Menus.................................................................................................................................................57
Menubars.......................................................................................................................................58
Menu Widgets and Hierarchy....................................................................................................58
Before you Start........................................................................................................................59
Creating a Menubar...................................................................................................................59
Adding Menus...........................................................................................................................60
Adding Menu Items..................................................................................................................60
Types of Menu Items.................................................................................................................60
3
Accelerator Keys.......................................................................................................................61
More on Item Options...............................................................................................................62
Underline..............................................................................................................................62
Images..................................................................................................................................62
State......................................................................................................................................62
Querying and Changing Item Options..................................................................................62
Platform Menus..............................................................................................................................63
Mac OS X..................................................................................................................................63
The Application Menu..........................................................................................................63
Handling the Preferences Menu Item...................................................................................64
Providing a Help Menu........................................................................................................64
Providing a Window Menu...................................................................................................65
Other Menu Handlers...........................................................................................................65
Windows....................................................................................................................................66
X11............................................................................................................................................66
Contextual Menus..........................................................................................................................67
Windows and Dialogs.........................................................................................................................67
Creating and Destroying Windows................................................................................................68
Changing Window Behavior and Styles........................................................................................68
Window Title........................................................................................................................68
Size and Location.................................................................................................................68
Stacking Order......................................................................................................................69
Resizing Behavior................................................................................................................70
Iconifying and Withdrawing.................................................................................................70
Standard Dialogs............................................................................................................................70
Selecting Files and Directories.............................................................................................70
Selecting Colors...................................................................................................................72
Alert and Confirmation Dialogs...........................................................................................73
Organizing Complex Interfaces..........................................................................................................74
Multiple windows.................................................................................................................74
White space..........................................................................................................................74
Separator........................................................................................................................................75
Label Frames..................................................................................................................................75
Paned Windows..............................................................................................................................76
Notebook........................................................................................................................................77
Fonts, Colors, Images.........................................................................................................................78
Fonts...............................................................................................................................................78
Standard Fonts...........................................................................................................................79
Platform-Specific Fonts............................................................................................................79
Named Fonts.............................................................................................................................80
Font Descriptions......................................................................................................................80
Colors.............................................................................................................................................81
Images............................................................................................................................................81
Problems with PIL/Pillow on Mac OS X?................................................................................82
Canvas................................................................................................................................................82
Creating Items................................................................................................................................83
Item Attributes...............................................................................................................................84
Bindings.........................................................................................................................................85
Tags................................................................................................................................................85
Modifying Items............................................................................................................................87
4
Scrolling.........................................................................................................................................87
Other Item Types............................................................................................................................89
Text.....................................................................................................................................................90
The Basics......................................................................................................................................90
Providing Initial Content...........................................................................................................91
Scrolling....................................................................................................................................91
Controlling Wrapping................................................................................................................91
Disabling the Widget.................................................................................................................91
Retrieving the Text....................................................................................................................91
Modifying the Text in Code...........................................................................................................92
Text Positions and Indices.........................................................................................................92
Deleting Text.............................................................................................................................93
Example: Logging Window......................................................................................................93
Formatting with Tags.....................................................................................................................94
Adding Tags to Text..................................................................................................................94
Applying Formatting to Tags....................................................................................................94
More Tag Manipulations...........................................................................................................95
Differences between Tags in Canvas and Text Widgets............................................................95
Events and Bindings......................................................................................................................96
Selecting Text.................................................................................................................................96
Marks.............................................................................................................................................96
Images and Widgets.......................................................................................................................97
Even More......................................................................................................................................98
Search........................................................................................................................................98
Modifications, Undo and Redo.................................................................................................98
Eliding Text...............................................................................................................................98
Introspection..............................................................................................................................98
Peering......................................................................................................................................98
Tree.....................................................................................................................................................99
Adding Items to the Tree...............................................................................................................99
Rearranging Items........................................................................................................................100
Displaying Information for each Item.........................................................................................100
Item Appearance and Events........................................................................................................101
Customizing the Display..............................................................................................................102
Styles and Themes............................................................................................................................102
Definitions...................................................................................................................................102
Widget Class...........................................................................................................................102
Widget State............................................................................................................................103
Style........................................................................................................................................104
Themes....................................................................................................................................104
Using Styles and Themes.............................................................................................................104
Style Names............................................................................................................................104
Using a Style...........................................................................................................................105
Using Themes..........................................................................................................................105
What's Inside a Style?..................................................................................................................106
Elements..................................................................................................................................106
Layout.....................................................................................................................................107
Element Options......................................................................................................................108
Changing Style Options...............................................................................................................108
Modifying a Style Option.......................................................................................................108
5
Creating a New, Derived Style................................................................................................109
State Specific Style Options....................................................................................................109
Sound Difficult to you?................................................................................................................110
Advanced: More on Elements......................................................................................................112
Case Study: IDLE Modernization....................................................................................................113
Project Goals................................................................................................................................115
Menus...........................................................................................................................................116
Main Window...............................................................................................................................117
Default Font.............................................................................................................................118
Around the Text Widget..........................................................................................................120
Preferences Dialog.......................................................................................................................122
Tabs.........................................................................................................................................125
Updating Widgets....................................................................................................................126
Layout.....................................................................................................................................126
Another Example....................................................................................................................128
Other Dialogs...............................................................................................................................130
Find Dialog.............................................................................................................................130
About Dialog...........................................................................................................................133
Online Help.............................................................................................................................136
Query Dialogs.........................................................................................................................137
Dialog Placement....................................................................................................................139
Window Integration.....................................................................................................................140
Tabbed Editor..........................................................................................................................141
Debugger.................................................................................................................................142
Integrated Shell and Debugger................................................................................................144
Workarounds, Hacks, and More...................................................................................................144
Tool Tips..................................................................................................................................144
Context Menus........................................................................................................................144
Peer Text Widgets....................................................................................................................144
Modal Windows......................................................................................................................144
6
Introduction
This tutorial is designed to help people get up to speed quickly with building mainstream desktop
graphical user interfaces with Tk, and in particular Tk 8.5, which is an incredibly significant
milestone release and a significant departure from the older versions of Tk which most people know
and love recognize.
The downside is that unless you know one or two particular things, it's actually not that significant a
release; For backwards compatibility reasons, unless existing programs make a few simple changes,
they won't look all that much different. So while this tutorial will certainly benefit newcomers to
Tk, it will also help existing Tk developers bring their knowledge right up to date. It's a cliche, but I
can't believe how much I've learned in writing this tutorial, and I've been using Tk for over fifteen
years.
The general state of Tk documentation (outside the Tcl-oriented reference documentation, which is
excellent) is unfortunately not at a high point these days. This is particularly true for developers
using Tk from languages other than Tcl, and developers working on multiple platforms.
So this tutorial will, as much as possible, target developers on the three main platforms (Windows,
Mac, Linux), and also be language-neutral. Initially, the tutorial will cover Tcl, Ruby, Perl and
Python. Over time, additional languages may be added. Even if your own language isn't included,
the chances are you'll still benefit; since all the languages use the same underlying Tk library, there's
obviously a lot of overlap.
This is also not a reference guide, it's not going to cover everything, just the essentials you need in
95% of applications. The rest you can find in reference documentation.
7
For most tools, you wouldn't think you'd have to say something like that, but for Tk that's not the
case. Tk has had a very long evolution (see Tk Backgrounder), and any evolution tends to leave you
with a bit of cruft; couple that with how much graphical user interface platforms and standards have
evolved in that time, and you can see where keeping something as large and complex as a GUI
library up to date as well as backwards compatible may be challenging.
Tk has, in recent years, gotten a bad rap, to put it mildly. Some of this has been well deserved, most
of it not so much. Like any GUI tool, it can be used to create absolutely terrible looking and
outdated user interfaces, but with the proper care and attention, it can also be used to create
spectacularly good ones as well. Most people know about the crappy ones; most of the good ones
people don't even know are done in Tk. In this tutorial, we're going to focus on what you need to
build good user interfaces, which isn't nearly as hard as it used to be before Tk 8.5.
So modern desktop graphical user interfaces, using modern conventions and design sense, using the
modern tools provided by Tk 8.5.
Tk Extensions
When it comes to modern best practices, Tk extensions deserve a special word of note. Over the
years, a number of groups have provided all kinds of add-ons to Tk, for example adding new
widgets not available in the core (or at least not at the time). Some well-known and quite popular
Tk extensions include BLT, Tix, iWidgets, BWidgets; there are many, many others.
Many of these extensions were created years ago. Because core Tk has always been highly
backwards compatible, these extensions generally continue to work with newer versions. However,
many have not been updated, or not been significantly updated, in a long time. They may not reflect
current platform conventions or styles, and so while they "work", they can make your application
appear extremely dated or out of place.
If you do decide to use Tk extensions, it's highly recommended that you investigate and review your
choices carefully.
8
documentation equivalent of opinionated software. So we'll often use different ways of doing things
than in other documentation or examples; often, it's because when those were written, the better
ways didn't even exist yet. Later on, once you're an expert, and you're encountering some wacky
situation where the normal choice doesn't fit, you can go hunt around for alternatives.
How to Use
While the tutorial is designed to be used linearly, feel free to jump around as you see fit. We'll often
provide links where you can go for more information, whether links to other documentation on this
site, such as our "widget roundup" providing usage info on each Tk widget, or to external
documentation, such as the full reference for a particular command.
The tutorial also lets you select what language (Tcl, Ruby, Perl or Python) to show. You can change
this by the "Show:" popup menu which is located in the sidebar, near the top right of each page in
the tutorial. But it also lets you see how Tk is used by all the different languages, which can itself be
quite interesting and useful.
Conventions
As is typically done, code listings, interpreter or shell commands and responses will be indicated
with a fixed-width font. When showing an interactive session with the interpreter, the parts
that you enter will additionally be in bold fixed-width.
When describing procedure or method calls, the literal parts (e.g. the method name) will be in plain
fixed-width font, parameters where you should fill in the actual value will add italics, and optional
parameters will be surrounded by '?', e.g. "set variable ?value?".
9
tend to get fixed up over time, it's worth marking them in your code with a "TODO" so you can
remember to go back later and see if a newer API resolves the problem cleanly.
Installing Tk
In this chapter, you'll get Tk installed on your machine, verify it works, and then see a quick
example of what a Tk program looks like.
Though pretty much all Mac OS X and Linux machines come with Tk installed already, it's often an
older version (typically 8.4.x). You want to make sure you've got at least version 8.5 (or possibly
8.6) to use the new widget set, so if that's not already there, you'll want to install the newer version.
Though there are lots of ways to install Tk, the easiest is to download and install one of the versions
provided by ActiveState (www.activestate.com).
ActiveState is a company that sells professional developer tools for dynamic languages. They also
provide (for free) quality-controlled distributions of some of these languages, and happen to employ
a number of core developers of these languages.
Installing Tk on Mac OS X
Tkinter (and, since Python 3.1, ttk) are included with all standard Python distributions on Mac OS
X. However, more recent distributions do not always include the underlying Tcl and Tk libraries
and support files, which must be installed separately.
While there are several different ways to do get Tcl and Tk onto your machine, the easiest and most
recommended is to use the ActiveTcl distribution.
If you're a masochist and want to read about other Tcl/Tk options and variations and how they
interact with Python, see the Mac Tcl/Tk page at python.org.
Install ActiveTcl
In your web browser, go to www.activestate.com, and follow along the links to download the
Community Edition of ActiveTcl, available as a universal binary. Make sure you're downloading an
8.5.x version, not an older 8.4.x version.
Run the installer to get Tcl and Tk loaded onto your machine.
Install Python
It is important that you use a version of Python supporting Tk 8.5 or greater, and ttk. We
recommend using the standard Python 3.x Mac installer that can be downloaded from python.org.
Earlier versions of this tutorial recommended using ActiveState's ActivePython. Older versions used
to include Tcl/Tk libraries and support files, but more recent versions no longer do, and require
10
downloading them separately, e.g. via ActiveTcl. Therefore the standard Python distribution works
just as well, and the end result is the same.
Run the installer and follow along. You'll end up with a fresh install of ActivePython in
/Library/Frameworks, along with links to the versioned Python binaries placed in /usr/local/bin (e.g.
'python3.4' if you downloaded ActivePython 3.4.x). From a Terminal window you should then be
able to run a Python shell:
% /usr/local/bin/python3.4
This should give you the Python command prompt. From the prompt, enter these two commands:
>>> import tkinter
>>> tkinter._test()
This should pop up a small window; the first line at the top of the window should say "This is
Tcl/Tk version 8.5"; make sure it is not 8.4!
You can also get the exact version of Tcl/Tk that is being used with:
>>> tkinter.Tcl().eval('info patchlevel')
Installing Tk on Windows
Tkinter (and, since Python 3.1, ttk) are included with all standard Python distributions. It is
important that you use a version of Python supporting Tk 8.5 or greater, and ttk. We recommend
using the standard Python 3.x Windows installer which can be downloaded from python.org.
Earlier versions of this tutorial recommended using the ActivePython distribution from ActiveState;
that will work as well. Both contain Python as well as the underlying Tcl/Tk libraries.
Run the installer, and follow along. You'll end up with a fresh install of ActivePython, located in,
e.g. C:\python34. From a Windows command prompt, or the Start Menu's "Run..." command, you
should then be able to run a Python shell via:
% C:\python34\python
This should give you the Python command prompt. From the prompt, enter these two commands:
>>> import tkinter
>>> tkinter._test()
This should pop up a small window; the first line at the top of the window should say "This is
Tcl/Tk version 8.5" (or "8.6"); make sure it is not 8.4!
You can also get the exact version of Tcl/Tk that is being used with:
11
>>> tkinter.Tcl().eval('info patchlevel')
Installing Tk on Linux
Tkinter (and, since Python 3.1, ttk) are included with all standard Python distributions. It is
important that you use a version of Python supporting Tk 8.5 or greater, and ttk. Many Python
distributions will not automatically install the underlying Tcl and Tk libraries however.
You have several different options to get Python and Tkinter onto your machine.
In this case, that package provides Tcl/Tk 8.6.1 libraries to be used with Python.
12
Option 3. Install Tcl/Tk and Compile the Standard Python Distribution
If you'd like to use the standard source distribution from python.org, you can certainly do that.
But to do so, you'll need to get the Tcl and Tk include files and libraries loaded on your machine
first. While there are again several ways to do that, the easiest is to download and install ActiveTcl.
In your web browser, go to www.activestate.com, and follow along the links to download the
Community Edition of ActiveTcl for Linux. Make sure you're downloading a 8.5 or newer version.
Unpack it, run the installer (./install.sh), and follow along. You'll end up with a fresh install of
ActiveTcl, located in e.g. /opt/ActiveTcl-8.5.
Next, download the current Python 3.x source distribution from python.org, and unpack it. On your
configure line, you'll need to tell it how to find the version of Tcl/Tk you installed. Then build as
usual:
% ./configure --with-tcltk-includes='-I/opt/ActiveTcl-8.5/include'
--with-tcltk-libs='/opt/ActiveTcl-8.5/lib/libtcl8.5.so /opt/ActiveTcl-
8.5/lib/libtk8.5.so'
% ./make
% ./make install
The most common thing is that the way you specified the Tcl/Tk include and libraries needs to be
changed somehow. Or if you get messages that certain include files can't be found (e.g.
"X11/Xlib.h") you may need to install additional packages on your Linux distribution (e.g. "apt-get
install libx11-dev"). Once you get it to compile without errors, don't forget to "make install".
This should pop up a small window; the first line at the top of the window should say "This is
Tcl/Tk version 8.5"; make sure it is not 8.4!
If it gives you an error when you try to 'import tkinter' (e.g. "If this fails your Python may not be
configured for Tk"), something hasn't been set up right. If you compiled Python yourself, see above
to check for compile errors.
You can also get the exact version of Tcl/Tk that is being used with:
>>> tkinter.Tcl().eval('info patchlevel')
13
which should return something like '8.5.18'.
Verified install using ActiveTcl 8.5.18, Python 3.4.3 from python.org on Ubuntu 14.04 LTS
Couldn't find hello.py? You might be looking in the wrong directory. Try providing the full path to
hello.py.
Design
The example we'll use is a simple GUI tool that will convert a number of feet to the equivalent
number of meters. If we were to sketch this out, it might look something like this:
14
A sketch of our feet to meters conversion program.
So it looks like we have a short text entry widget that will let us type in the number of feet, and a
'Calculate' button that will get the value out of that entry, perform the calculation, and then put the
resulting number of meters on the screen just below where the entry is. We've also got three static
labels ("feet", "is equivalent to", and "meters") which help our user figure out how to use the
interface.
In terms of layout, things seem to naturally divide into three columns and three rows:
Code
Now here is the Python code to create this program.
from tkinter import *
from tkinter import ttk
def calculate(*args):
try:
value = float(feet.get())
meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
except ValueError:
pass
root = Tk()
root.title("Feet to Meters")
15
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
feet = StringVar()
meters = StringVar()
feet_entry.focus()
root.bind('<Return>', calculate)
root.mainloop()
Screenshot of our completed feet to meters user interface (on Mac OS X, Windows and Linux).
16
Step-by-Step Walkthrough
Let's take a closer look at that code, piece by piece. For now, all we're trying to do is get a basic
understanding of the types of things we need to do to create a user interface in Tk, and roughly what
those things look like. We'll go into details later.
from tkinter import *
from tkinter import ttk
These two lines tell Python that our program needs two modules. The first, "tkinter", is the
standard binding to Tk, which when loaded also causes the existing Tk library on your system to be
loaded. The second, "ttk", is Python's binding to the newer "themed widgets" that were added to
Tk in 8.5.
Notice that we've imported everything from the tkinter module, so that we can call tkinter functions
etc. without prefixing them, which is standard Tkinter practice. However, because we've imported
just "ttk" itself, that means we'll need to prefix anything inside that module. So for example
calling "Entry(...)" would invoke the function inside the tkinter module, while we'd need
"ttk.Entry(...)" to invoke the function inside ttk. As you'll see, several functions are
defined in both modules, and sometimes you will need both, depending on the context. Making the
ttk calls explicit facilitates this, and will be the style used in this tutorial.
One of the first things you'll find if you're migrating new code over, is that the name of the Tkinter
module is now lowercase, i.e. "tkinter", rather than "Tkinter". This was changed as of Python 3.0.
root = Tk()
root.title("Feet to Meters")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
Yes, the "calculate" function appeared before this. We'll describe it down below, but need to
include it near the start because we reference it in other parts of the program.
Next, the above lines set up the main window, giving it the title "Feet to Meters". Next, we create a
frame widget, which will hold all the content of our user interface, and place that in our main
window. The "columnconfigure"/"rowconfigure" bits just tell Tk that if the main
window is resized, the frame should expand to take up the extra space.
Strictly speaking, we could just put the other parts of our interface directly into the main root
window, without the intervening content frame. However, the main window isn't itself part of the
"themed" widgets, so its background color wouldn't match the themed widgets we will put inside it.
Using a "themed" frame widget to hold the content ensures that the background is correct.
feet = StringVar()
meters = StringVar()
feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))
ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
17
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3,
sticky=W)
The preceding lines create the three main widgets in our program: the entry where we type the
number of feet in, a label where we put the resulting number of meters, and the calculate button that
we press to perform the calculation.
For each of the three widgets, we need to do two things: create the widget itself, and then place it
onscreen. All three widgets, which are 'children' of our content window are created as instances of
one of Tk's themed widget classes. At the same time as we create them, we give them certain
options, such as how wide the entry is, the text to put inside the Button, etc. The entry and label
each are assigned a mysterious "textvariable"; we'll see what that does shortly.
If the widgets are just created, they won't automatically show up on screen, because Tk doesn't
know how you want them to be placed relative to other widgets. That's what the "grid" part does.
Remembering the layout grid for our application, we place each widget in the appropriate column
(1, 2 or 3), and row (also 1, 2 or 3). The "sticky" option says how the widget would line up
within the grid cell, using compass directions. So "w" (west) means anchor the widget to the left
side of the cell, "we" (west-east) means anchor it to both the left and right sides, and so on.
ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W)
The above three lines do exactly the same thing for the three static text labels in our user interface;
create each one, and place it onscreen in the appropriate cell in the grid.
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
feet_entry.focus()
root.bind('<Return>', calculate)
The preceeding three lines help put some nice finishing touches on our user interface.
The first line walks through all of the widgets that are children of our content frame, and adds a
little bit of padding around each, so they aren't so scrunched together. We could have added these
options to each "grid" call when we first put the widgets onscreen, but this is a nice shortcut.
The second line tells Tk to put the focus on our entry widget. That way the cursor will start in that
field, so the user doesn't have to click in it before starting to type.
The third line tells Tk that if the user presses the Return key (Enter on Windows) anywhere within
the root window, that it should call our calculate routine, the same as if the user pressed the
Calculate button.
def calculate(*args):
try:
value = float(feet.get())
meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
except ValueError:
pass
18
Here we define our calculate procedure, which is called either when the user presses the Calculate
button, or hits the Return key. It performs the feet to meters calculation, taking the number of feet
from our entry widget, and placing the result in our label widget.
Say what? It doesn't look like we're doing anything with those widgets! Here's where the magic
"textvariable" options we specified when creating the widgets come into play. We specified
the global variable "feet" as the textvariable for the entry, which means that anytime the entry
changes, Tk will automatically update the global variable feet. Similarly, if we explicitly change the
value of a textvariable associated with a widget (as we're doing for "meters" which is attached to
our label), the widget will automatically be updated with the current contents of the variable. Slick.
root.mainloop()
This final line tells Tk to enter its event loop, which is needed to make everything run.
What's Missing
It's also worth examing what we didn't have to include in our Tk program to make it work. For
example:
• we didn't have to worry about redrawing the screen as things changed
• we didn't have to worry about parsing and dispatching events, hit detection, or handling
events on each widget
• we didn't have to provide a lot of options when we created widgets; the defaults seemed to
take care of most things, and so we only had to change things like the text the button
displayed
• we didn't have to write complex code to get and set the values of simple widgets; we just
attached them to variables
• we didn't have to worry about what happens when the user closes the window or resizes it
• we didn't need to write extra code to get this all to work cross-platform
Tk Concepts
With a first example behind you, you should have a basic idea of what a Tk program might look like
and the types of tasks it needs to accomplish. We'll step back and look at three broad concepts that
you need to know to understand Tk: widgets, geometry management, and event handling.
Widgets
Widgets are all the things that you see onscreen. In our example, we had a button, an entry, a few
labels, and a frame. Others are things like checkboxes, tree views, scrollbars, text areas, and so on.
19
Widgets are what are often referred to as "controls"; you'll also often see them referred to as
"windows", particularly in Tk's documentation, a holdover from its X11 roots (so under that
terminology, both a toplevel window and things like a button would be called windows).
Here is an example showing some of Tk's widgets, which we'll cover individually shortly.
Several Tk Widgets.
Widget Classes
Widgets are objects, instances of classes that represent buttons, frames, and so on. So the first thing
you'll need to do is identify the specific class of the widget you'd like to instantiate. This tutorial and
the widget roundup will help with that.
Window Hierarchy
The other thing you'll need to know is the parent of the widget instance you'd like to create. In Tk,
all widgets are part of a window hierarchy, with a single root at the top of the hierarchy. This
hierarchy can be arbitrarily deep; so you might have a button in a frame in another frame within the
root window. Even a new toplevel window is part of that same hierarchy, with it and all its contents
forming a subtree of the overall window hierarchy.
In our metric conversion example, we had a single frame that was created as a child of the root
window, and that frame had all the other controls as children. The root window was a container for
the frame, and was therefore the frame's parent. The complete hierarchy for the example looked like
this:
20
Random documents with unrelated
content Scribd suggests to you:
MOI. Or la femme est un être humain et social; elle a donc un droit
absolu à cette égalité sans laquelle, dans la société, elle ne serait
qu'une paria.
MOI. Fi! mon Maître. Vous contredire de la sorte est honteux pour
votre réputation. Il aurait mieux valu soutenir que la femme n'a pas
les mêmes droits que l'homme, parce qu'elle est d'une autre espèce.
MOI. Niez et outragez; cela ne nous fait rien, Maître: les seigneurs
usaient de cette méthode contre vos pères leurs serfs... aujourd'hui
on s'indigne contre eux. Les possesseurs d'esclaves usaient et usent
de cette méthode contre les noirs, et le monde civilisé s'indigne
contre eux, l'esclavage est restreint et tend à disparaître.
En attendant je signale à mes lecteurs vos contradictions: votre
autorité sur les esprits en sera, j'espère, amoindrie.
Ceux qui prétendront, d'après la majeure des syllogismes
précédents, que vous fondez le droit sur l'identité d'espèce,
abstraction faite des qualités individuelles; que vous croyez le droit
et le devoir corrélatifs, que vous voulez l'égalité, la liberté, auront
tout aussi raison que ceux qui prétendront, d'après la conclusion des
mêmes syllogismes, que vous basez le droit sur la force, la
supériorité des facultés; que vous acceptez l'inégalité, le despotisme,
niez la liberté individuelle et l'égalité sociale, et ne croyez point à la
corrélation du droit et du devoir.
S'il est triste pour vous d'être tombé dans des contradictions aussi
monstrueuses, croyez qu'il ne l'est pas moins pour moi, dans l'intérêt
de ma cause, de les signaler devant tous.
Prenant en main la cause de mon sexe, j'étais dans l'obligation de
riposter à vos attaques, en retournant contre vous toutes vos
allégations contre nous.
Il fallait le faire, non par des dénégations et des déclamations qui ne
prouvent rien, ou par des affirmations sans preuves selon votre
procédé; mais en vous opposant la science et les faits; en ne me
servant que de la méthode rationnelle que vous préconisez sans
vous en servir, en vous chargeant souvent de vous contredire quand
les preuves de fait eussent demandé trop de détail et de temps.
Vous accusiez les femmes de prendre des chimères pour des
réalités... Je vous ai prouvé que vous méritez ce reproche, puisque
votre théorie est en contradiction avec la science et les faits.
Vous accusiez les femmes d'ériger en principes de vaines analogies...
Je vous ai prouvé que vous en avez fait autant, en induisant de la
prétendue absence de germes physiques chez la femme, l'absence
de germes intellectuels et moraux.
Vous accusiez la femme de raisonner à contre sens.... je vous ai mis
en présence de vos propres principes, pour en tirer des
conséquences contradictoires.
Vous accusiez la femme de ne faire que des Macédoines, des
Monstres... L'anatomie de votre théorie prouve que vous en savez
faire tout autant.
Vous accusiez la femme d'inintelligence, de défaut de justice, de
vertu, de chasteté... J'en appelle à vous même, et vous dites
positivement le contraire.
Où vous êtes fantasque, contradictoire, j'en appelle moi, femme, à la
logique.
Où vous manquez de méthode, moi, femme, j'emploie la méthode
scientifique et rationnelle.
Où vous démentez vos propres principes, j'en appelle à ces mêmes
principes pour vous juger et vous condamner.
Lequel de nous deux, Monsieur, est le plus raisonnable et le plus
rationnel?
Ma modestie souffre, je vous l'avoue, de penser que j'ai joué le rôle
de Minerve faisant honte à Ulysse de ses paradoxes et de ses
roueries. Enfin, cet ennuyeux rôle est fini!
Je vous ai adressé tant de duretés, et d'un ton si ferme et si résolu,
que j'aurais regret de vous quitter sans vous dire quelques bonnes
paroles partant du fond de mon cœur. Vous devez être bien
convaincu de ma sincérité, car vous voyez que vous avez affaire à
une femme qui ne recule devant personne; qu'on n'intimide pas,
quelque grand qu'on soit et quelque nom qu'on porte. Vous pouvez
être mon adversaire: je ne serai jamais votre ennemie, car je vous
estime comme un honnête homme, un vigoureux penseur, une des
gloires de la France, une des illustrations de notre Comté, toujours si
chère au cœur de ses enfants, enfin comme une des admirations de
ma jeunesse. Vous et moi, M. Proudhon, nous appartenons à la
grande armée qui donne l'assaut à la citadelle des abus et y porte la
mine et la sape: je ne fuis pas cette solidarité. Est-il donc si
nécessaire que nous nous battions? Vivons en paix; je puis vous en
prier sans m'abaisser, puisque je ne vous crains pas. Comprenez une
chose que je vous dis sans fiel: c'est que vous êtes incapable de
comprendre la femme, et qu'en continuant la lutte, vous la rangerez
immanquablement sous la bannière de la Contre-Révolution.
Votre orgueil a mis inimitié entre vous et la femme, et vous lui avez
mordu le talon: personne ne serait plus affligé que moi de la voir
vous écraser la tête.
RÉSUMÉ.
M. LEGOUVÉ, souriant. Vous allez bien vite et bien loin mon cher
Monsieur; vous effarouchez tout le monde. Au fond du cœur, je crois
bien comme vous à l'égalité des sexes par l'équivalence des
fonctions, mais je me garde bien d'en souffler mot. Je me contente
de réclamer pour les femmes l'instruction, une diminution de servage
conjugal et des emplois de charité: comptant bien, entre nous, que,
ces conquêtes obtenues, les femmes seront en mesure, par leur
instruction et leur utilité constatée, de s'affranchir tout à fait. Eh
bien! malgré ma réserve et ma modération, vous verrez que les uns
me traiteront de femmelin, les autres de sans-culotte!
A mes lecteurs 5
A mes adversaires 9
A mes amis 11
PREMIÈRE PARTIE.
Communistes modernes 17
Saint-Simoniens 24
Fusioniens 37
Phalanstériens 44
M. Ernest Legouvé 56
M. É. de Girardin 78
M. Michelet 91
M. A. Comte 110
M. Proudhon 126
Résumé 221
ERRATA.
Page 10, ligne 1, au lieu de: ne sachant pas écrire, lisez: ne sachant
pas même écrire.
Page 21, ligne 27, au lieu de: brave Jeanne Durain, lisez: brave
Jeanne Deroin.
Page 101, ligne 3, au lieu de: une borne pierre, lisez: une bonne
pierre.
Page 106, ligne 18, au lieu de: aient appartenu, lisez: n'aient
appartenu.
Page 107, ligne 27, au lieu de: devaient être, lisez: doivent être.
Page 124, ligne 26, au lieu de: que'éducation, lisez: qu'éducation.
Page 142, ligne 12, au lieu de: de régir, lisez: de se régir.
Page 163, ligne 5, au lieu de: je le tiendra, lisez: je le tiendrai.
Page 194, ligne 6, au lieu de: ne sont que de, lisez: ne sont que des.
Page 207, ligne 28, au lieu de: ubstance, lisez: substance.
*** END OF THE PROJECT GUTENBERG EBOOK LA FEMME
AFFRANCHIE, VOL. 1 OF 2 ***
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com