Tkinter rename reversal: remove tkinter package, adapt imports and docs.

This commit is contained in:
Georg Brandl 2008-05-20 07:13:37 +00:00
parent 33cece05b9
commit 6634bf2919
74 changed files with 227 additions and 7971 deletions

View File

@ -3,13 +3,13 @@
Other Graphical User Interface Packages
=======================================
There are an number of extension widget sets to :mod:`tkinter`.
There are an number of extension widget sets to :mod:`Tkinter`.
.. seealso::
`Python megawidgets <http://pmw.sourceforge.net/>`_
is a toolkit for building high-level compound widgets in Python using the
:mod:`tkinter` package. It consists of a set of base classes and a library of
:mod:`Tkinter` module. It consists of a set of base classes and a library of
flexible and extensible megawidgets built on this foundation. These megawidgets
include notebooks, comboboxes, selection widgets, paned widgets, scrolled
widgets, dialog windows, etc. Also, with the Pmw.Blt interface to BLT, the

View File

@ -1,27 +1,17 @@
:mod:`tkinter.scrolledtext` --- Scrolled Text Widget
====================================================
:mod:`ScrolledText` --- Scrolled Text Widget
============================================
.. module:: ScrolledText
:synopsis: Old name for the tkinter.scrolledtext module.
.. module:: tkinter.scrolledtext
:platform: Tk
:synopsis: Text widget with a vertical scroll bar.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. note::
The :mod:`ScrolledText` module has been renamed to
:mod:`tkinter.scrolledtext` in Python 3.0. It is importable under both names
in Python 2.6 and the rest of the 2.x series.
The :mod:`tkinter.scrolledtext` module provides a class of the same name which
The :mod:`ScrolledText` module provides a class of the same name which
implements a basic text widget which has a vertical scroll bar configured to do
the "right thing." Using the :class:`ScrolledText` class is a lot easier than
setting up a text widget and scroll bar directly. The constructor is the same
as that of the :class:`tkinter.Text` class.
.. versionchanged:: 2.6
Renamed from ``ScrolledText``.
as that of the :class:`Tkinter.Text` class.
The text widget and scrollbar are packed together in a :class:`Frame`, and the
methods of the :class:`Grid` and :class:`Pack` geometry managers are acquired

View File

@ -1,28 +1,20 @@
:mod:`tkinter.tix` --- Extension widgets for Tk
===============================================
:mod:`Tix` --- Extension widgets for Tk
=======================================
.. module:: Tix
:synopsis: Old name for the tkinter.tix module.
.. module:: tkinter.tix
:synopsis: Tk Extension Widgets for Tkinter
.. sectionauthor:: Mike Clarkson <mikeclarkson@users.sourceforge.net>
.. note::
The :mod:`Tix` module has been renamed to :mod:`tkinter.tix` in Python 3.0.
It is importable under both names in Python 2.6 and the rest of the 2.x
series.
.. index:: single: Tix
The :mod:`tkinter.tix` (Tk Interface Extension) module provides an additional
rich set of widgets. Although the standard Tk library has many useful widgets,
they are far from complete. The :mod:`tkinter.tix` library provides most of the
commonly needed widgets that are missing from standard Tk: :class:`HList`,
:class:`ComboBox`, :class:`Control` (a.k.a. SpinBox) and an assortment of
scrollable widgets.
:mod:`tkinter.tix` also includes many more widgets that are generally useful in
a wide range of applications: :class:`NoteBook`, :class:`FileEntry`,
The :mod:`Tix` (Tk Interface Extension) module provides an additional rich set
of widgets. Although the standard Tk library has many useful widgets, they are
far from complete. The :mod:`Tix` library provides most of the commonly needed
widgets that are missing from standard Tk: :class:`HList`, :class:`ComboBox`,
:class:`Control` (a.k.a. SpinBox) and an assortment of scrollable widgets.
:mod:`Tix` also includes many more widgets that are generally useful in a wide
range of applications: :class:`NoteBook`, :class:`FileEntry`,
:class:`PanedWindow`, etc; there are more than 40 of them.
With all these new widgets, you can introduce new interaction techniques into
@ -30,6 +22,7 @@ applications, creating more useful and more intuitive user interfaces. You can
design your application by choosing the most appropriate widgets to match the
special needs of your application and users.
.. seealso::
`Tix Homepage <http://tix.sourceforge.net/>`_
@ -57,27 +50,27 @@ Using Tix
Toplevel widget of Tix which represents mostly the main window of an
application. It has an associated Tcl interpreter.
Classes in the :mod:`tkinter.tix` module subclasses the classes in the
:mod:`tkinter`. The former imports the latter, so to use :mod:`tkinter.tix`
with Tkinter, all you need to do is to import one module. In general, you
can just import :mod:`tkinter.tix`, and replace the toplevel call to
:class:`tkinter.Tk` with :class:`tix.Tk`::
Classes in the :mod:`Tix` module subclasses the classes in the :mod:`Tkinter`
module. The former imports the latter, so to use :mod:`Tix` with Tkinter, all
you need to do is to import one module. In general, you can just import
:mod:`Tix`, and replace the toplevel call to :class:`Tkinter.Tk` with
:class:`Tix.Tk`::
from tkinter import tix
from tkinter.constants import *
root = tix.Tk()
import Tix
from Tkconstants import *
root = Tix.Tk()
To use :mod:`tkinter.tix`, you must have the Tix widgets installed, usually
To use :mod:`Tix`, you must have the :mod:`Tix` widgets installed, usually
alongside your installation of the Tk widgets. To test your installation, try
the following::
from tkinter import tix
root = tix.Tk()
import Tix
root = Tix.Tk()
root.tk.eval('package require Tix')
If this fails, you have a Tk installation problem which must be resolved before
proceeding. Use the environment variable :envvar:`TIX_LIBRARY` to point to the
installed Tix library directory, and make sure you have the dynamic
installed :mod:`Tix` library directory, and make sure you have the dynamic
object library (:file:`tix8183.dll` or :file:`libtix8183.so`) in the same
directory that contains your Tk dynamic object library (:file:`tk8183.dll` or
:file:`libtk8183.so`). The directory with the dynamic object library should also
@ -92,8 +85,8 @@ Tix Widgets
`Tix <http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm>`_
introduces over 40 widget classes to the :mod:`Tkinter` repertoire. There is a
demo of all the :mod:`tkinter.tix` widgets in the :file:`Demo/tix` directory of
the standard distribution.
demo of all the :mod:`Tix` widgets in the :file:`Demo/tix` directory of the
standard distribution.
.. The Python sample code is still being added to Python, hence commented out
@ -441,11 +434,11 @@ Manager Widgets
Image Types
^^^^^^^^^^^
The :mod:`tkinter.tix` module adds:
The :mod:`Tix` module adds:
* `pixmap <http://tix.sourceforge.net/dist/current/man/html/TixCmd/pixmap.htm>`_
capabilities to all :mod:`tkinter.tix` and :mod:`tkinter` widgets to create
color images from XPM files.
capabilities to all :mod:`Tix` and :mod:`Tkinter` widgets to create color images
from XPM files.
.. Python Demo of:
.. \ulink{XPM Image In Button}{http://tix.sourceforge.net/dist/current/demos/samples/Xpm.tcl}
@ -485,7 +478,7 @@ Miscellaneous Widgets
Form Geometry Manager
^^^^^^^^^^^^^^^^^^^^^
In addition, :mod:`tkinter.tix` augments :mod:`tkinter` by providing:
In addition, :mod:`Tix` augments :mod:`Tkinter` by providing:
.. class:: Form()

View File

@ -12,20 +12,19 @@ Graphical User Interfaces with Tk
Tk/Tcl has long been an integral part of Python. It provides a robust and
platform independent windowing toolkit, that is available to Python programmers
using the :mod:`tkinter` package, and its extension, the :mod:`tkinter.tix`
module.
using the :mod:`Tkinter` module, and its extension, the :mod:`Tix` module.
The :mod:`tkinter` package is a thin object-oriented layer on top of Tcl/Tk. To
use :mod:`tkinter`, you don't need to write Tcl code, but you will need to
The :mod:`Tkinter` module is a thin object-oriented layer on top of Tcl/Tk. To
use :mod:`Tkinter`, you don't need to write Tcl code, but you will need to
consult the Tk documentation, and occasionally the Tcl documentation.
:mod:`tkinter` is a set of wrappers that implement the Tk widgets as Python
:mod:`Tkinter` is a set of wrappers that implement the Tk widgets as Python
classes. In addition, the internal module :mod:`_tkinter` provides a threadsafe
mechanism which allows Python and Tcl to interact.
:mod:`tkinter`'s chief virtues are that it is fast, and that it usually comes
:mod:`Tkinter`'s chief virtues are that it is fast, and that it usually comes
bundled with Python. Although its standard documentation is weak, good
material is available, which includes: references, tutorials, a book and
others. :mod:`tkinter` is also famous for having an outdated look and feel,
others. :mod:`Tkinter` is also famous for having an outdated look and feel,
which has been vastly improved in Tk 8.5. Nevertheless, there are many other
GUI libraries that you could be interested in. For more information about
alternatives, see the :ref:`other-gui-packages` section.
@ -33,9 +32,9 @@ alternatives, see the :ref:`other-gui-packages` section.
.. toctree::
tkinter.rst
tkinter.tix.rst
tkinter.scrolledtext.rst
tkinter.turtle.rst
tix.rst
scrolledtext.rst
turtle.rst
idle.rst
othergui.rst

View File

@ -1,26 +1,16 @@
:mod:`tkinter` --- Python interface to Tcl/Tk
:mod:`Tkinter` --- Python interface to Tcl/Tk
=============================================
.. module:: Tkinter
:synopsis: Old name for the tkinter module.
.. module:: tkinter
:synopsis: Interface to Tcl/Tk for graphical user interfaces
.. moduleauthor:: Guido van Rossum <guido@Python.org>
The :mod:`tkinter` package ("Tk interface") is the standard Python interface to
the Tk GUI toolkit. Both Tk and :mod:`tkinter` are available on most Unix
The :mod:`Tkinter` module ("Tk interface") is the standard Python interface to
the Tk GUI toolkit. Both Tk and :mod:`Tkinter` are available on most Unix
platforms, as well as on Windows and Macintosh systems. (Tk itself is not part
of Python; it is maintained at ActiveState.)
.. note::
The :mod:`Tkinter` module has been renamed to a :mod:`tkinter` package in
Python 3.0. All other Tkinter-related modules have been moved to submodules
within that package (see their individual descriptions).
All modules are importable under both names in Python 2.6 and the rest of the
2.x series.
.. seealso::
@ -44,23 +34,23 @@ of Python; it is maintained at ActiveState.)
Tkinter Modules
---------------
Most of the time, the :mod:`tkinter` is all you really need, but a number
Most of the time, the :mod:`Tkinter` module is all you really need, but a number
of additional modules are available as well. The Tk interface is located in a
binary module named :mod:`_tkinter`. This module contains the low-level
interface to 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.
In addition to the Tk interface module, :mod:`tkinter` includes a number of
Python modules, :mod:`tkinter.constants` being one of the most important.
Importing :mod:`tkinter` will automatically import :mod:`tkinter.constants`,
so, usually, to use Tkinter all you need is a simple import statement::
In addition to the Tk interface module, :mod:`Tkinter` includes a number of
Python modules. The two most important modules are the :mod:`Tkinter` module
itself, and a module called :mod:`Tkconstants`. The former automatically imports
the latter, so to use Tkinter, all you need to do is to import one module::
import tkinter
import Tkinter
Or, more often::
from tkinter import *
from Tkinter import *
.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)
@ -89,67 +79,41 @@ Or, more often::
Other modules that provide Tk support include:
:mod:`tkinter.scrolledtext`
:mod:`ScrolledText`
Text widget with a vertical scroll bar built in.
.. versionchanged:: 2.6
Renamed from ``ScrolledText``.
:mod:`tkinter.colorchooser`
:mod:`tkColorChooser`
Dialog to let the user choose a color.
.. versionchanged:: 2.6
Renamed from ``tkColorChooser``.
:mod:`commondialog`
:mod:`tkCommonDialog`
Base class for the dialogs defined in the other modules listed here.
.. versionchanged:: 2.6
Renamed from ``tkCommonDialog``.
:mod:`filedialog`
:mod:`tkFileDialog`
Common dialogs to allow the user to specify a file to open or save.
.. versionchanged:: 2.6
Renamed from ``tkFileDialog``.
:mod:`tkinter.font`
:mod:`tkFont`
Utilities to help work with fonts.
.. versionchanged:: 2.6
Renamed from ``tkFont``.
:mod:`tkinter.messagebox`
:mod:`tkMessageBox`
Access to standard Tk dialog boxes.
.. versionchanged:: 2.6
Renamed from ``tkMessageBox``.
:mod:`tkinter.simpledialog`
:mod:`tkSimpleDialog`
Basic dialogs and convenience functions.
.. versionchanged:: 2.6
Renamed from ``tkSimpleDialog``.
:mod:`Tkdnd`
Drag-and-drop support for :mod:`Tkinter`. This is experimental and should become
deprecated when it is replaced with the Tk DND.
:mod:`tkinter.dnd`
Drag-and-drop support for :mod:`tkinter`. This is experimental and should
become deprecated when it is replaced with the Tk DND.
.. versionchanged:: 2.6
Renamed from ``Tkdnd``.
:mod:`tkinter.turtle`
:mod:`turtle`
Turtle graphics in a Tk window.
.. versionchanged:: 2.6
Renamed from ``turtle``.
Tkinter Life Preserver
----------------------
.. sectionauthor:: Matt Conway
This section is not designed to be an exhaustive tutorial on either Tk or
Tkinter. Rather, it is intended as a stop gap, providing some introductory
orientation on the system.
@ -181,7 +145,7 @@ handy reference.
When trying to answer questions of the form "how do I do blah", it is often best
to find out how to do"blah" in straight Tk, and then convert this back into the
corresponding :mod:`tkinter` call. Python programmers can often guess at the
corresponding :mod:`Tkinter` call. Python programmers can often guess at the
correct Python command by looking at the Tk documentation. This means that in
order to use Tkinter, you will have to know a little bit about Tk. This document
can't fulfill that role, so the best we can do is point you to the best
@ -197,8 +161,8 @@ documentation that exists. Here are some hints:
the novice. The book is not exhaustive, and for many details it defers to the
man pages.
* :file:`tkinter/__init__.py` is a last resort for most, but can be a good
place to go when nothing else makes sense.
* :file:`Tkinter.py` is a last resort for most, but can be a good place to go
when nothing else makes sense.
.. seealso::
@ -218,7 +182,7 @@ A Simple Hello World Program
::
from tkinter import *
from Tkinter import *
class Application(Frame):
def say_hi(self):
@ -272,7 +236,7 @@ Notes:
To make use of this reference material, there will be times when you will need
to know how to read short passages of Tk and how to identify the various parts
of a Tk command. (See section :ref:`tkinter-basic-mapping` for the
:mod:`tkinter` equivalents of what's below.)
:mod:`Tkinter` equivalents of what's below.)
Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
of tokens separated by spaces. A Tk widget is just its *class*, the *options*
@ -360,9 +324,9 @@ module. ::
To give a widget to the packer (geometry manager), you call pack with optional
arguments. In Tkinter, the Pack class holds all this functionality, and the
various forms of the pack command are implemented as methods. All widgets in
:mod:`tkinter` are subclassed from the Packer, and so inherit all the packing
methods. See the :mod:`tkinter.tix` module documentation for additional
information on the Form geometry manager. ::
:mod:`Tkinter` are subclassed from the Packer, and so inherit all the packing
methods. See the :mod:`Tix` module documentation for additional information on
the Form geometry manager. ::
pack .fred -side left =====> fred.pack(side = "left")
@ -373,11 +337,11 @@ How Tk and Tkinter are Related
From the top down:
Your App Here (Python)
A Python application makes a :mod:`tkinter` call.
A Python application makes a :mod:`Tkinter` call.
tkinter (Python Package)
Tkinter (Python Module)
This call (say, for example, creating a button widget), is implemented in the
*tkinter* package, which is written in Python. This Python function will parse
*Tkinter* module, which is written in Python. This Python function will parse
the commands and the arguments and convert them into a form that makes them look
as if they had come from a Tk script instead of a Python script.
@ -389,8 +353,8 @@ Tk Widgets (C and Tcl)
This C function is able to make calls into other C modules, including the C
functions that make up the Tk library. Tk is implemented in C and some Tcl.
The Tcl part of the Tk widgets is used to bind certain default behaviors to
widgets, and is executed once at the point where the Python :mod:`tkinter`
package is imported. (The user never sees this stage).
widgets, and is executed once at the point where the Python :mod:`Tkinter`
module is imported. (The user never sees this stage).
Tk (C)
The Tk part of the Tk Widgets implement the final mapping to ...
@ -546,11 +510,11 @@ options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
``value``. This connection works both ways: if the variable changes for any
reason, the widget it's connected to will be updated to reflect the new value.
Unfortunately, in the current implementation of :mod:`tkinter` it is not
Unfortunately, in the current implementation of :mod:`Tkinter` it is not
possible to hand over an arbitrary Python variable to a widget through a
``variable`` or ``textvariable`` option. The only kinds of variables for which
this works are variables that are subclassed from a class called Variable,
defined in the :mod:`tkinter`.
defined in the :mod:`Tkinter` module.
There are many useful subclasses of Variable already defined:
:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
@ -594,7 +558,7 @@ The Window Manager
In Tk, there is a utility command, ``wm``, for interacting with the window
manager. Options to the ``wm`` command allow you to control things like titles,
placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have
placement, icon bitmaps, and the like. In :mod:`Tkinter`, these commands have
been implemented as methods on the :class:`Wm` class. Toplevel widgets are
subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
directly.
@ -608,7 +572,7 @@ part of the implementation, and not an interface to Tk functionality.
Here are some examples of typical usage::
from tkinter import *
from Tkinter import *
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
@ -769,7 +733,7 @@ Entry widget, or to particular menu items in a Menu widget.
Entry widget indexes (index, view index, etc.)
Entry widgets have options that refer to character positions in the text being
displayed. You can use these :mod:`tkinter` functions to access these special
displayed. You can use these :mod:`Tkinter` functions to access these special
points in text widgets:
AtEnd()
@ -821,7 +785,7 @@ Images
^^^^^^
Bitmap/Pixelmap images can be created through the subclasses of
:class:`tkinter.Image`:
:class:`Tkinter.Image`:
* :class:`BitmapImage` can be used for X11 bitmap data.

View File

@ -1,34 +1,24 @@
:mod:`tkinter.turtle` --- Turtle graphics for Tk
================================================
:mod:`turtle` --- Turtle graphics for Tk
========================================
.. module:: turtle
:synopsis: Old name for the tkinter.turtle module.
.. module:: tkinter.turtle
:platform: Tk
:synopsis: An environment for turtle graphics.
.. moduleauthor:: Guido van Rossum <guido@python.org>
.. note::
The :mod:`turtle` module has been renamed to :mod:`tkinter.turtle` in Python
3.0. It is importable under both names in Python 2.6 and the rest of the 2.x
series.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
The :mod:`tkinter.turtle` module provides turtle graphics primitives, in both an
object-oriented and procedure-oriented ways. Because it uses :mod:`tkinter` for
The :mod:`turtle` module provides turtle graphics primitives, in both an
object-oriented and procedure-oriented ways. Because it uses :mod:`Tkinter` for
the underlying graphics, it needs a version of python installed with Tk support.
.. versionchanged:: 2.6
Renamed from ``turtle``.
The procedural interface uses a pen and a canvas which are automagically created
when any of the functions are called.
The :mod:`tkinter.turtle` module defines the following functions:
The :mod:`turtle` module defines the following functions:
.. function:: degrees()

View File

@ -1,7 +1,7 @@
"""
An auto-completion window for IDLE, used by the AutoComplete extension
"""
from tkinter import *
from Tkinter import *
from MultiCall import MC_SHIFT
import AutoComplete

View File

@ -4,7 +4,7 @@ After ToolTip.py, which uses ideas gleaned from PySol
Used by the CallTips IDLE extension.
"""
from tkinter import *
from Tkinter import *
HIDE_VIRTUAL_EVENT_NAME = "<<calltipwindow-hide>>"
HIDE_SEQUENCES = ("<Key-Escape>", "<FocusOut>")

View File

@ -9,8 +9,8 @@ variable in the CodeContext section of config-extensions.def. Lines which do
not open blocks are not shown in the context hints pane.
"""
import tkinter
from tkinter.constants import TOP, LEFT, X, W, SUNKEN
import Tkinter
from Tkconstants import TOP, LEFT, X, W, SUNKEN
from configHandler import idleConf
import re
from sys import maxint as INFINITY
@ -69,7 +69,7 @@ class CodeContext:
border = 0
for widget in widgets:
border += int(str( widget.cget('border') ))
self.label = tkinter.Label(self.editwin.top,
self.label = Tkinter.Label(self.editwin.top,
text="\n" * (self.context_depth - 1),
anchor=W, justify=LEFT,
font=self.textfont,

View File

@ -2,7 +2,7 @@ import time
import re
import keyword
import __builtin__
from tkinter import *
from Tkinter import *
from Delegator import Delegator
from configHandler import idleConf

View File

@ -1,7 +1,7 @@
import os
import bdb
import types
from tkinter import *
from Tkinter import *
from WindowList import ListedToplevel
from ScrolledList import ScrolledList
import macosxSupport

View File

@ -3,9 +3,9 @@ import os
import re
import imp
from itertools import count
from tkinter import *
import tkinter.simpledialog as tkSimpleDialog
import tkinter.messagebox as tkMessageBox
from Tkinter import *
import tkSimpleDialog
import tkMessageBox
from MultiCall import MultiCallCreator
import webbrowser
@ -45,7 +45,7 @@ class EditorWindow(object):
from UndoDelegator import UndoDelegator
from IOBinding import IOBinding, filesystemencoding, encoding
import Bindings
from tkinter import Toplevel
from Tkinter import Toplevel
from MultiStatusBar import MultiStatusBar
help_url = None

View File

@ -1,6 +1,6 @@
import os
from tkinter import *
import tkinter.messagebox as tkMessageBox
from Tkinter import *
import tkMessageBox
class FileList:

View File

@ -1,7 +1,7 @@
import os
import fnmatch
import sys
from tkinter import *
from Tkinter import *
import SearchEngine
from SearchDialogBase import SearchDialogBase

View File

@ -10,11 +10,11 @@ import types
import sys
import codecs
import tempfile
import tkinter.filedialog as tkFileDialog
import tkinter.messagebox as tkMessageBox
import tkFileDialog
import tkMessageBox
import re
from tkinter import *
from tkinter.simpledialog import SimpleDialog
from Tkinter import *
from SimpleDialog import SimpleDialog
from configHandler import idleConf

View File

@ -32,7 +32,7 @@ Each function will be called at most once for each event.
import sys
import string
import re
import tkinter
import Tkinter
# the event type constants, which define the meaning of mc_type
MC_KEYPRESS=0; MC_KEYRELEASE=1; MC_BUTTONPRESS=2; MC_BUTTONRELEASE=3;
@ -292,7 +292,7 @@ def MultiCallCreator(widget):
return _multicall_dict[widget]
class MultiCall (widget):
assert issubclass(widget, tkinter.Misc)
assert issubclass(widget, Tkinter.Misc)
def __init__(self, *args, **kwargs):
apply(widget.__init__, (self,)+args, kwargs)
@ -382,8 +382,8 @@ def MultiCallCreator(widget):
if __name__ == "__main__":
# Test
root = tkinter.Tk()
text = MultiCallCreator(tkinter.Text)(root)
root = Tkinter.Tk()
text = MultiCallCreator(Tkinter.Text)(root)
text.pack()
def bindseq(seq, n=[0]):
def handler(event):

View File

@ -1,4 +1,4 @@
from tkinter import *
from Tkinter import *
class MultiStatusBar(Frame):

View File

@ -136,7 +136,7 @@ def make_objecttreeitem(labeltext, object, setfunction=None):
def _test():
import sys
from tkinter import Tk
from Tkinter import Tk
root = Tk()
root.configure(bd=0, bg="yellow")
root.focus_set()

View File

@ -1,7 +1,7 @@
from tkinter import *
from Tkinter import *
from EditorWindow import EditorWindow
import re
import tkinter.messagebox as tkMessageBox
import tkMessageBox
import IOBinding
class OutputWindow(EditorWindow):

View File

@ -81,5 +81,5 @@ def main():
root.mainloop()
if __name__ == "__main__":
from tkinter import *
from Tkinter import *
main()

View File

@ -17,12 +17,12 @@ import linecache
from code import InteractiveInterpreter
try:
from tkinter import *
from Tkinter import *
except ImportError:
print>>sys.__stderr__, "** IDLE can't import tkinter. " \
print>>sys.__stderr__, "** IDLE can't import Tkinter. " \
"Your Python may not be configured for Tk. **"
sys.exit(1)
import tkinter.messagebox as tkMessageBox
import tkMessageBox
from EditorWindow import EditorWindow, fixwordbreaks
from FileList import FileList
@ -992,8 +992,8 @@ class PyShell(OutputWindow):
(sys.version, sys.platform, self.COPYRIGHT,
self.firewallmessage, idlever.IDLE_VERSION, nosub))
self.showprompt()
import tkinter
tkinter._default_root = None # 03Jan04 KBK What's this?
import Tkinter
Tkinter._default_root = None # 03Jan04 KBK What's this?
return True
def readline(self):

View File

@ -1,4 +1,4 @@
from tkinter import *
from Tkinter import *
import SearchEngine
from SearchDialogBase import SearchDialogBase

View File

@ -22,7 +22,7 @@ import re
import string
import tabnanny
import tokenize
import tkinter.messagebox as tkMessageBox
import tkMessageBox
import PyShell
from configHandler import idleConf

View File

@ -1,4 +1,4 @@
from tkinter import *
from Tkinter import *
class ScrolledList:

View File

@ -1,4 +1,4 @@
from tkinter import *
from Tkinter import *
import SearchEngine
from SearchDialogBase import SearchDialogBase

View File

@ -1,4 +1,4 @@
from tkinter import *
from Tkinter import *
class SearchDialogBase:

View File

@ -1,6 +1,6 @@
import re
from tkinter import *
import tkinter.messagebox as tkMessageBox
from Tkinter import *
import tkMessageBox
def get(root):
if not hasattr(root, "_searchengine"):

View File

@ -7,7 +7,7 @@ from ObjectBrowser import ObjectTreeItem, make_objecttreeitem
def StackBrowser(root, flist=None, tb=None, top=None):
if top is None:
from tkinter import Toplevel
from Tkinter import Toplevel
top = Toplevel(root)
sc = ScrolledCanvas(top, bg="white", highlightthickness=0)
sc.frame.pack(expand=1, fill="both")
@ -128,7 +128,7 @@ def _test():
reload(testcode)
except:
sys.last_type, sys.last_value, sys.last_traceback = sys.exc_info()
from tkinter import Tk
from Tkinter import Tk
root = Tk()
StackBrowser(None, top=root)
root.mainloop()

View File

@ -3,7 +3,7 @@
# may be useful for some purposes in (or almost in ;) the current project scope
# Ideas gleaned from PySol
from tkinter import *
from Tkinter import *
class ToolTipBase:

View File

@ -15,7 +15,7 @@
# - optimize tree redraw after expand of subnode
import os
from tkinter import *
from Tkinter import *
import imp
import ZoomHeight

View File

@ -1,5 +1,5 @@
import string
from tkinter import *
from Tkinter import *
from Delegator import Delegator
#$ event <<redo>>

View File

@ -1,4 +1,4 @@
from tkinter import *
from Tkinter import *
class WidgetRedirector:

View File

@ -1,4 +1,4 @@
from tkinter import *
from Tkinter import *
class WindowList:

View File

@ -2,7 +2,7 @@
"""
from tkinter import *
from Tkinter import *
import os
import os.path
import textView

View File

@ -9,10 +9,8 @@ Note that tab width in IDLE is currently fixed at eight due to Tk issues.
Refer to comments in EditorWindow autoindent code for details.
"""
from tkinter import *
import tkinter.messagebox as tkMessageBox
import tkinter.colorchooser as tkColorChooser
import tkinter.font as tkFont
from Tkinter import *
import tkMessageBox, tkColorChooser, tkFont
import string
from configHandler import idleConf

View File

@ -3,9 +3,9 @@
import os
import sys
from tkinter import *
import tkinter.messagebox as tkMessageBox
import tkinter.filedialog as tkFileDialog
from Tkinter import *
import tkMessageBox
import tkFileDialog
class GetHelpSourceDialog(Toplevel):
def __init__(self, parent, title, menuItem='', filePath=''):

View File

@ -2,8 +2,8 @@
Dialog that allows user to specify a new config file section name.
Used to get new highlight theme and keybinding set names.
"""
from tkinter import *
import tkinter.messagebox as tkMessageBox
from Tkinter import *
import tkMessageBox
class GetCfgSectionNameDialog(Toplevel):
def __init__(self,parent,title,message,usedNames):

View File

@ -2,8 +2,8 @@
OptionMenu widget modified to allow dynamic menu reconfiguration
and setting of highlightthickness
"""
from tkinter import OptionMenu
from tkinter import _setit
from Tkinter import OptionMenu
from Tkinter import _setit
import copy
class DynOptionMenu(OptionMenu):

View File

@ -1,8 +1,8 @@
"""
Dialog for building Tkinter accelerator key bindings
"""
from tkinter import *
import tkinter.messagebox as tkMessageBox
from Tkinter import *
import tkMessageBox
import string
class GetKeysDialog(Toplevel):

View File

@ -3,7 +3,7 @@ A number of function that enhance IDLE on MacOSX when it used as a normal
GUI application (as opposed to an X11 application).
"""
import sys
import tkinter
import Tkinter
def runningAsOSXApp():
""" Returns True iff running from the IDLE.app bundle on OSX """
@ -26,7 +26,7 @@ def addOpenEventSupport(root, flist):
def hideTkConsole(root):
try:
root.tk.call('console', 'hide')
except tkinter.TclError:
except Tkinter.TclError:
# Some versions of the Tk framework don't have a console object
pass
@ -46,7 +46,7 @@ def overrideRootMenu(root, flist):
#
# Due to a (mis-)feature of TkAqua the user will also see an empty Help
# menu.
from tkinter import Menu, Text, Text
from Tkinter import Menu, Text, Text
from EditorWindow import prepstr, get_accelerator
import Bindings
import WindowList

View File

@ -127,9 +127,9 @@ def manage_socket(address):
server.handle_request() # A single request only
def show_socket_error(err, address):
import tkinter
import tkinter.messagebox as tkMessageBox
root = tkinter.Tk()
import Tkinter
import tkMessageBox
root = Tkinter.Tk()
root.withdraw()
if err[0] == 61: # connection refused
msg = "IDLE's subprocess can't connect to %s:%d. This may be due "\

View File

@ -7,7 +7,7 @@ TabbedPageSet -- A Tkinter implementation of a tabbed-page widget.
TabSet -- A widget containing tabs (buttons) in one or more rows.
"""
from tkinter import *
from Tkinter import *
class InvalidNameError(Exception): pass
class AlreadyExistsError(Exception): pass

View File

@ -2,8 +2,8 @@
"""
from tkinter import *
import tkinter.messagebox as tkMessageBox
from Tkinter import *
import tkMessageBox
class TextViewer(Toplevel):
"""A simple text viewer dialog for IDLE
@ -68,7 +68,7 @@ def view_file(parent, title, filename, encoding=None):
else:
textFile = open(filename, 'r')
except IOError:
import tkinter.messagebox as tkMessageBox
import tkMessageBox
tkMessageBox.showerror(title='File Load Error',
message='Unable to load file %r .' % filename,
parent=parent)

View File

@ -7,7 +7,7 @@ from warnings import warnpy3k
warnpy3k("the Canvas module has been removed in Python 3.0", stacklevel=2)
del warnpy3k
from tkinter import Canvas, _cnfmerge, _flatten
from Tkinter import Canvas, _cnfmerge, _flatten
class CanvasItem:

View File

@ -1,7 +1,7 @@
# dialog.py -- Tkinter interface to the tk_dialog script.
from tkinter import *
from tkinter import _cnfmerge
from Tkinter import *
from Tkinter import _cnfmerge
if TkVersion <= 3.6:
DIALOG_ICON = 'warning'

View File

@ -10,8 +10,8 @@
# Most methods calls are inherited from the Text widget; Pack methods
# are redirected to the Frame widget however.
from tkinter import *
from tkinter import _cnfmerge
from Tkinter import *
from Tkinter import _cnfmerge
class ScrolledText(Text):
def __init__(self, master=None, cnf=None, **kw):

View File

@ -26,8 +26,8 @@
# appreciate the advantages.
#
from tkinter import *
from tkinter import _flatten, _cnfmerge, _default_root
from Tkinter import *
from Tkinter import _flatten, _cnfmerge, _default_root
# WARNING - TkVersion is a limited precision floating point number
if TkVersion < 3.999:
@ -57,7 +57,7 @@ TCL_ALL_EVENTS = 0
# BEWARE - this is implemented by copying some code from the Widget class
# in Tkinter (to override Widget initialization) and is therefore
# liable to break.
import tkinter, os
import Tkinter, os
# Could probably add this to Tkinter.Misc
class tixCommand:
@ -192,11 +192,11 @@ class tixCommand:
else:
return self.tk.call('tix', 'resetoptions', newScheme, newFontSet)
class Tk(tkinter.Tk, tixCommand):
class Tk(Tkinter.Tk, tixCommand):
"""Toplevel widget of Tix which represents mostly the main window
of an application. It has an associated Tcl interpreter."""
def __init__(self, screenName=None, baseName=None, className='Tix'):
tkinter.Tk.__init__(self, screenName, baseName, className)
Tkinter.Tk.__init__(self, screenName, baseName, className)
tixlib = os.environ.get('TIX_LIBRARY')
self.tk.eval('global auto_path; lappend auto_path [file dir [info nameof]]')
if tixlib is not None:
@ -212,7 +212,7 @@ class Tk(tkinter.Tk, tixCommand):
def destroy(self):
# For safety, remove an delete_window binding before destroy
self.protocol("WM_DELETE_WINDOW", "")
tkinter.Tk.destroy(self)
Tkinter.Tk.destroy(self)
# The Tix 'tixForm' geometry manager
class Form:
@ -260,9 +260,9 @@ class Form:
tkinter.Widget.__bases__ = tkinter.Widget.__bases__ + (Form,)
Tkinter.Widget.__bases__ = Tkinter.Widget.__bases__ + (Form,)
class TixWidget(tkinter.Widget):
class TixWidget(Tkinter.Widget):
"""A TixWidget class is used to package all (or most) Tix widgets.
Widget initialization is extended in two ways:
@ -383,7 +383,7 @@ class TixWidget(tkinter.Widget):
# These are missing from Tkinter
def image_create(self, imgtype, cnf={}, master=None, **kw):
if not master:
master = tkinter._default_root
master = Tkinter._default_root
if not master:
raise RuntimeError, 'Too early to create image'
if kw and cnf: cnf = _cnfmerge((cnf, kw))

View File

@ -100,7 +100,7 @@ active; it will never call dnd_commit().
"""
import tkinter
import Tkinter
# The factory function
@ -219,7 +219,7 @@ class Icon:
self.detach()
if not canvas:
return
label = tkinter.Label(canvas, text=self.name,
label = Tkinter.Label(canvas, text=self.name,
borderwidth=2, relief="raised")
id = canvas.create_window(x, y, window=label, anchor="nw")
self.canvas = canvas
@ -268,8 +268,8 @@ class Icon:
class Tester:
def __init__(self, root):
self.top = tkinter.Toplevel(root)
self.canvas = tkinter.Canvas(self.top, width=100, height=100)
self.top = Tkinter.Toplevel(root)
self.canvas = Tkinter.Canvas(self.top, width=100, height=100)
self.canvas.pack(fill="both", expand=1)
self.canvas.dnd_accept = self.dnd_accept
@ -300,9 +300,9 @@ class Tester:
source.attach(self.canvas, x, y)
def test():
root = tkinter.Tk()
root = Tkinter.Tk()
root.geometry("+1+1")
tkinter.Button(command=root.quit, text="Quit").pack()
Tkinter.Button(command=root.quit, text="Quit").pack()
t1 = Tester(root)
t1.top.geometry("+1+60")
t2 = Tester(root)

View File

@ -18,14 +18,14 @@ Actions are bound to events by resources (e.g. keyword argument
command) or with the method bind.
Example (Hello, World):
import tkinter
from tkinter.constants import *
tk = tkinter.Tk()
frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
import Tkinter
from Tkconstants import *
tk = Tkinter.Tk()
frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
frame.pack(fill=BOTH,expand=1)
label = tkinter.Label(frame, text="Hello, World")
label = Tkinter.Label(frame, text="Hello, World")
label.pack(fill=X, expand=1)
button = tkinter.Button(frame,text="Exit",command=tk.destroy)
button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
button.pack(side=BOTTOM)
tk.mainloop()
"""
@ -35,11 +35,12 @@ __version__ = "$Revision$"
import sys
if sys.platform == "win32":
# Attempt to configure Tcl/Tk without requiring PATH
from tkinter import _fix
import FixTk
import _tkinter # If this fails your Python may not be configured for Tk
tkinter = _tkinter # b/w compat for export
TclError = _tkinter.TclError
from types import *
from tkinter.constants import *
from Tkconstants import *
try:
import MacOS; _MacOS = MacOS; del MacOS
except ImportError:
@ -1697,7 +1698,7 @@ class Tk(Misc, Wm):
base_tcl = os.path.join(home, '.%s.tcl' % baseName)
base_py = os.path.join(home, '.%s.py' % baseName)
dir = {'self': self}
exec 'from tkinter import *' in dir
exec 'from Tkinter import *' in dir
if os.path.isfile(class_tcl):
self.tk.call('source', class_tcl)
if os.path.isfile(class_py):

View File

@ -19,7 +19,7 @@
# - title: dialog title
#
from tkinter.commondialog import Dialog
from tkCommonDialog import Dialog
#

View File

@ -1,14 +1,14 @@
# base class for tk common dialogues
#
# this module provides a base class for accessing the common
# dialogues available in Tk 4.2 and newer. use filedialog,
# colorchooser, and messagebox to access the individual
# dialogues available in Tk 4.2 and newer. use tkFileDialog,
# tkColorChooser, and tkMessageBox to access the individual
# dialogs.
#
# written by Fredrik Lundh, May 1997
#
from tkinter import *
from Tkinter import *
class Dialog:

View File

@ -8,7 +8,7 @@
__version__ = "0.9"
import tkinter
import Tkinter
# weight/slant
NORMAL = "normal"
@ -31,7 +31,7 @@ class Font:
name -- name to use for this font configuration (defaults to a unique name)
exists -- does a named font by this name already exist?
Creates a new named font if False, points to the existing font if True.
Raises _tkinter.TclError if the assertion is false.
Raises _Tkinter.TclError if the assertion is false.
the following are ignored if font is specified:
@ -65,7 +65,7 @@ class Font:
def __init__(self, root=None, font=None, name=None, exists=False, **options):
if not root:
root = tkinter._default_root
root = Tkinter._default_root
if font:
# get actual settings corresponding to the given font
font = root.tk.splitlist(root.tk.call("font", "actual", font))
@ -79,7 +79,7 @@ class Font:
self.delete_font = False
# confirm font exists
if self.name not in root.tk.call("font", "names"):
raise tkinter._tkinter.TclError, "named font %s does not already exist" % (self.name,)
raise Tkinter._tkinter.TclError, "named font %s does not already exist" % (self.name,)
# if font config info supplied, apply it
if font:
root.tk.call("font", "configure", self.name, *font)
@ -166,13 +166,13 @@ class Font:
def families(root=None):
"Get font families (as a tuple)"
if not root:
root = tkinter._default_root
root = Tkinter._default_root
return root.tk.splitlist(root.tk.call("font", "families"))
def names(root=None):
"Get names of defined fonts (as a tuple)"
if not root:
root = tkinter._default_root
root = Tkinter._default_root
return root.tk.splitlist(root.tk.call("font", "names"))
# --------------------------------------------------------------------
@ -180,7 +180,7 @@ def names(root=None):
if __name__ == "__main__":
root = tkinter.Tk()
root = Tkinter.Tk()
# create a font
f = Font(family="times", size=30, weight=NORMAL)
@ -202,10 +202,10 @@ if __name__ == "__main__":
f = Font(font=("Courier", 20, "bold"))
print f.measure("hello"), f.metrics("linespace")
w = tkinter.Label(root, text="Hello, world", font=f)
w = Tkinter.Label(root, text="Hello, world", font=f)
w.pack()
w = tkinter.Button(root, text="Quit!", command=root.destroy)
w = Tkinter.Button(root, text="Quit!", command=root.destroy)
w.pack()
fb = Font(font=w["font"]).copy()
@ -213,4 +213,4 @@ if __name__ == "__main__":
w.config(font=fb)
tkinter.mainloop()
Tkinter.mainloop()

View File

@ -22,7 +22,7 @@
# - type: dialog type; that is, which buttons to display (see below)
#
from tkinter.commondialog import Dialog
from Tkinter.commondialog import Dialog
#
# constants

View File

@ -16,7 +16,7 @@ pictures can easily be drawn.
from math import * # Also for export
from time import sleep
import tkinter
import Tkinter
speeds = ['fastest', 'fast', 'normal', 'slow', 'slowest']
@ -238,7 +238,7 @@ class RawPen:
# Test the color first
try:
id = self._canvas.create_line(0, 0, 0, 0, fill=color)
except tkinter.TclError:
except Tkinter.TclError:
raise Error, "bad color string: %r" % (color,)
self._set_color(color)
return
@ -554,7 +554,7 @@ class RawPen:
# in case nhops==0
self._canvas.coords(item, x0, y0, x1, y1)
self._canvas.itemconfigure(item, arrow="none")
except tkinter.TclError:
except Tkinter.TclError:
# Probably the window was closed!
return
else:
@ -638,13 +638,13 @@ class Pen(RawPen):
def __init__(self):
global _root, _canvas
if _root is None:
_root = tkinter.Tk()
_root = Tkinter.Tk()
_root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
_root.title(_title)
if _canvas is None:
# XXX Should have scroll bars
_canvas = tkinter.Canvas(_root, background="white")
_canvas = Tkinter.Canvas(_root, background="white")
_canvas.pack(expand=1, fill="both")
setup(width=_width, height= _height, startx=_startx, starty=_starty)

View File

@ -2017,20 +2017,20 @@ def gui():
self.server = None
self.scanner = None
import tkinter
self.server_frm = tkinter.Frame(window)
self.title_lbl = tkinter.Label(self.server_frm,
import Tkinter
self.server_frm = Tkinter.Frame(window)
self.title_lbl = Tkinter.Label(self.server_frm,
text='Starting server...\n ')
self.open_btn = tkinter.Button(self.server_frm,
self.open_btn = Tkinter.Button(self.server_frm,
text='open browser', command=self.open, state='disabled')
self.quit_btn = tkinter.Button(self.server_frm,
self.quit_btn = Tkinter.Button(self.server_frm,
text='quit serving', command=self.quit, state='disabled')
self.search_frm = tkinter.Frame(window)
self.search_lbl = tkinter.Label(self.search_frm, text='Search for')
self.search_ent = tkinter.Entry(self.search_frm)
self.search_frm = Tkinter.Frame(window)
self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
self.search_ent = Tkinter.Entry(self.search_frm)
self.search_ent.bind('<Return>', self.search)
self.stop_btn = tkinter.Button(self.search_frm,
self.stop_btn = Tkinter.Button(self.search_frm,
text='stop', pady=0, command=self.stop, state='disabled')
if sys.platform == 'win32':
# Trying to hide and show this button crashes under Windows.
@ -2049,17 +2049,17 @@ def gui():
self.search_ent.focus_set()
font = ('helvetica', sys.platform == 'win32' and 8 or 10)
self.result_lst = tkinter.Listbox(window, font=font, height=6)
self.result_lst = Tkinter.Listbox(window, font=font, height=6)
self.result_lst.bind('<Button-1>', self.select)
self.result_lst.bind('<Double-Button-1>', self.goto)
self.result_scr = tkinter.Scrollbar(window,
self.result_scr = Tkinter.Scrollbar(window,
orient='vertical', command=self.result_lst.yview)
self.result_lst.config(yscrollcommand=self.result_scr.set)
self.result_frm = tkinter.Frame(window)
self.goto_btn = tkinter.Button(self.result_frm,
self.result_frm = Tkinter.Frame(window)
self.goto_btn = Tkinter.Button(self.result_frm,
text='go to selected', command=self.goto)
self.hide_btn = tkinter.Button(self.result_frm,
self.hide_btn = Tkinter.Button(self.result_frm,
text='hide results', command=self.hide)
self.goto_btn.pack(side='left', fill='x', expand=1)
self.hide_btn.pack(side='right', fill='x', expand=1)
@ -2179,9 +2179,9 @@ def gui():
self.stop()
self.collapse()
import tkinter
import Tkinter
try:
root = tkinter.Tk()
root = Tkinter.Tk()
# Tk will crash if pythonw.exe has an XP .manifest
# file and the root has is not destroyed explicitly.
# If the problem is ever fixed in Tk, the explicit

View File

@ -218,23 +218,7 @@ class TestStdlibRenames(unittest.TestCase):
renames = {'copy_reg': 'copyreg', 'Queue': 'queue',
'SocketServer': 'socketserver',
'ConfigParser': 'configparser',
'repr': 'reprlib',
'FileDialog': 'tkinter.filedialog',
'FixTk': 'tkinter._fix',
'ScrolledText': 'tkinter.scrolledtext',
'SimpleDialog': 'tkinter.simpledialog',
'Tix': 'tkinter.tix',
'tkColorChooser': 'tkinter.colorchooser',
'tkCommonDialog': 'tkinter.commondialog',
'Tkconstants': 'tkinter.constants',
'Tkdnd': 'tkinter.dnd',
'tkFileDialog': 'tkinter.filedialog',
'tkFont': 'tkinter.font',
'Tkinter': 'tkinter',
'tkMessageBox': 'tkinter.messagebox',
'tkSimpleDialog': 'tkinter.simpledialog',
'turtle': 'tkinter.turtle'
}
'repr': 'reprlib'}
def check_rename(self, module_name, new_module_name):
"""Make sure that:

View File

@ -3,7 +3,7 @@
import unittest
import os
from test import test_support
from tkinter import Tcl
from Tkinter import Tcl
from _tkinter import TclError
class TclTest(unittest.TestCase):

File diff suppressed because it is too large Load Diff

View File

@ -1,41 +0,0 @@
import sys, os
# Delay import _tkinter until we have set TCL_LIBRARY,
# so that Tcl_FindExecutable has a chance to locate its
# encoding directory.
# Unfortunately, we cannot know the TCL_LIBRARY directory
# if we don't know the tcl version, which we cannot find out
# without import Tcl. Fortunately, Tcl will itself look in
# <TCL_LIBRARY>\..\tcl<TCL_VERSION>, so anything close to
# the real Tcl library will do.
prefix = os.path.join(sys.prefix,"tcl")
if not os.path.exists(prefix):
# devdir/../tcltk/lib
prefix = os.path.join(sys.prefix, os.path.pardir, "tcltk", "lib")
prefix = os.path.abspath(prefix)
# if this does not exist, no further search is needed
if os.path.exists(prefix):
if not os.environ.has_key("TCL_LIBRARY"):
for name in os.listdir(prefix):
if name.startswith("tcl"):
tcldir = os.path.join(prefix,name)
if os.path.isdir(tcldir):
os.environ["TCL_LIBRARY"] = tcldir
# Compute TK_LIBRARY, knowing that it has the same version
# as Tcl
import _tkinter
ver = str(_tkinter.TCL_VERSION)
if not os.environ.has_key("TK_LIBRARY"):
v = os.path.join(prefix, 'tk'+ver)
if os.path.exists(os.path.join(v, "tclIndex")):
os.environ['TK_LIBRARY'] = v
# We don't know the Tix version, so we must search the entire
# directory
if not os.environ.has_key("TIX_LIBRARY"):
for name in os.listdir(prefix):
if name.startswith("tix"):
tixdir = os.path.join(prefix,name)
if os.path.isdir(tixdir):
os.environ["TIX_LIBRARY"] = tixdir

View File

@ -1,70 +0,0 @@
# tk common colour chooser dialogue
#
# this module provides an interface to the native color dialogue
# available in Tk 4.2 and newer.
#
# written by Fredrik Lundh, May 1997
#
# fixed initialcolor handling in August 1998
#
#
# options (all have default values):
#
# - initialcolor: colour to mark as selected when dialog is displayed
# (given as an RGB triplet or a Tk color string)
#
# - parent: which window to place the dialog on top of
#
# - title: dialog title
#
from tkinter.commondialog import Dialog
#
# color chooser class
class Chooser(Dialog):
"Ask for a color"
command = "tk_chooseColor"
def _fixoptions(self):
try:
# make sure initialcolor is a tk color string
color = self.options["initialcolor"]
if type(color) == type(()):
# assume an RGB triplet
self.options["initialcolor"] = "#%02x%02x%02x" % color
except KeyError:
pass
def _fixresult(self, widget, result):
# to simplify application code, the color chooser returns
# an RGB tuple together with the Tk color string
if not result:
return None, None # canceled
r, g, b = widget.winfo_rgb(result)
return (r/256, g/256, b/256), result
#
# convenience stuff
def askcolor(color = None, **options):
"Ask for a color"
if color:
options = options.copy()
options["initialcolor"] = color
return Chooser(**options).show()
# --------------------------------------------------------------------
# test stuff
if __name__ == "__main__":
print "color", askcolor()

View File

@ -1,60 +0,0 @@
# base class for tk common dialogues
#
# this module provides a base class for accessing the common
# dialogues available in Tk 4.2 and newer. use filedialog,
# colorchooser, and messagebox to access the individual
# dialogs.
#
# written by Fredrik Lundh, May 1997
#
from tkinter import *
class Dialog:
command = None
def __init__(self, master=None, **options):
# FIXME: should this be placed on the module level instead?
if TkVersion < 4.2:
raise TclError, "this module requires Tk 4.2 or newer"
self.master = master
self.options = options
if not master and options.get('parent'):
self.master = options['parent']
def _fixoptions(self):
pass # hook
def _fixresult(self, widget, result):
return result # hook
def show(self, **options):
# update instance options
for k, v in options.items():
self.options[k] = v
self._fixoptions()
# we need a dummy widget to properly process the options
# (at least as long as we use Tkinter 1.63)
w = Frame(self.master)
try:
s = w.tk.call(self.command, *w._options(self.options))
s = self._fixresult(w, s)
finally:
try:
# get rid of the widget
w.destroy()
except:
pass
return s

View File

@ -1,110 +0,0 @@
# Symbolic constants for Tk
# Booleans
NO=FALSE=OFF=0
YES=TRUE=ON=1
# -anchor and -sticky
N='n'
S='s'
W='w'
E='e'
NW='nw'
SW='sw'
NE='ne'
SE='se'
NS='ns'
EW='ew'
NSEW='nsew'
CENTER='center'
# -fill
NONE='none'
X='x'
Y='y'
BOTH='both'
# -side
LEFT='left'
TOP='top'
RIGHT='right'
BOTTOM='bottom'
# -relief
RAISED='raised'
SUNKEN='sunken'
FLAT='flat'
RIDGE='ridge'
GROOVE='groove'
SOLID = 'solid'
# -orient
HORIZONTAL='horizontal'
VERTICAL='vertical'
# -tabs
NUMERIC='numeric'
# -wrap
CHAR='char'
WORD='word'
# -align
BASELINE='baseline'
# -bordermode
INSIDE='inside'
OUTSIDE='outside'
# Special tags, marks and insert positions
SEL='sel'
SEL_FIRST='sel.first'
SEL_LAST='sel.last'
END='end'
INSERT='insert'
CURRENT='current'
ANCHOR='anchor'
ALL='all' # e.g. Canvas.delete(ALL)
# Text widget and button states
NORMAL='normal'
DISABLED='disabled'
ACTIVE='active'
# Canvas state
HIDDEN='hidden'
# Menu item types
CASCADE='cascade'
CHECKBUTTON='checkbutton'
COMMAND='command'
RADIOBUTTON='radiobutton'
SEPARATOR='separator'
# Selection modes for list boxes
SINGLE='single'
BROWSE='browse'
MULTIPLE='multiple'
EXTENDED='extended'
# Activestyle for list boxes
# NONE='none' is also valid
DOTBOX='dotbox'
UNDERLINE='underline'
# Various canvas styles
PIESLICE='pieslice'
CHORD='chord'
ARC='arc'
FIRST='first'
LAST='last'
BUTT='butt'
PROJECTING='projecting'
ROUND='round'
BEVEL='bevel'
MITER='miter'
# Arguments to xview/yview
MOVETO='moveto'
SCROLL='scroll'
UNITS='units'
PAGES='pages'

View File

@ -1,49 +0,0 @@
# dialog.py -- Tkinter interface to the tk_dialog script.
from tkinter import *
from tkinter import _cnfmerge
if TkVersion <= 3.6:
DIALOG_ICON = 'warning'
else:
DIALOG_ICON = 'questhead'
class Dialog(Widget):
def __init__(self, master=None, cnf={}, **kw):
cnf = _cnfmerge((cnf, kw))
self.widgetName = '__dialog__'
Widget._setup(self, master, cnf)
self.num = self.tk.getint(
self.tk.call(
'tk_dialog', self._w,
cnf['title'], cnf['text'],
cnf['bitmap'], cnf['default'],
*cnf['strings']))
try: Widget.destroy(self)
except TclError: pass
def destroy(self): pass
def _test():
d = Dialog(None, {'title': 'File Modified',
'text':
'File "Python.h" has been modified'
' since the last time it was saved.'
' Do you want to save it before'
' exiting the application.',
'bitmap': DIALOG_ICON,
'default': 0,
'strings': ('Save File',
'Discard Changes',
'Return to Editor')})
print d.num
if __name__ == '__main__':
t = Button(None, {'text': 'Test',
'command': _test,
Pack: {}})
q = Button(None, {'text': 'Quit',
'command': t.quit,
Pack: {}})
t.mainloop()

View File

@ -1,321 +0,0 @@
"""Drag-and-drop support for Tkinter.
This is very preliminary. I currently only support dnd *within* one
application, between different windows (or within the same window).
I an trying to make this as generic as possible -- not dependent on
the use of a particular widget or icon type, etc. I also hope that
this will work with Pmw.
To enable an object to be dragged, you must create an event binding
for it that starts the drag-and-drop process. Typically, you should
bind <ButtonPress> to a callback function that you write. The function
should call Tkdnd.dnd_start(source, event), where 'source' is the
object to be dragged, and 'event' is the event that invoked the call
(the argument to your callback function). Even though this is a class
instantiation, the returned instance should not be stored -- it will
be kept alive automatically for the duration of the drag-and-drop.
When a drag-and-drop is already in process for the Tk interpreter, the
call is *ignored*; this normally averts starting multiple simultaneous
dnd processes, e.g. because different button callbacks all
dnd_start().
The object is *not* necessarily a widget -- it can be any
application-specific object that is meaningful to potential
drag-and-drop targets.
Potential drag-and-drop targets are discovered as follows. Whenever
the mouse moves, and at the start and end of a drag-and-drop move, the
Tk widget directly under the mouse is inspected. This is the target
widget (not to be confused with the target object, yet to be
determined). If there is no target widget, there is no dnd target
object. If there is a target widget, and it has an attribute
dnd_accept, this should be a function (or any callable object). The
function is called as dnd_accept(source, event), where 'source' is the
object being dragged (the object passed to dnd_start() above), and
'event' is the most recent event object (generally a <Motion> event;
it can also be <ButtonPress> or <ButtonRelease>). If the dnd_accept()
function returns something other than None, this is the new dnd target
object. If dnd_accept() returns None, or if the target widget has no
dnd_accept attribute, the target widget's parent is considered as the
target widget, and the search for a target object is repeated from
there. If necessary, the search is repeated all the way up to the
root widget. If none of the target widgets can produce a target
object, there is no target object (the target object is None).
The target object thus produced, if any, is called the new target
object. It is compared with the old target object (or None, if there
was no old target widget). There are several cases ('source' is the
source object, and 'event' is the most recent event object):
- Both the old and new target objects are None. Nothing happens.
- The old and new target objects are the same object. Its method
dnd_motion(source, event) is called.
- The old target object was None, and the new target object is not
None. The new target object's method dnd_enter(source, event) is
called.
- The new target object is None, and the old target object is not
None. The old target object's method dnd_leave(source, event) is
called.
- The old and new target objects differ and neither is None. The old
target object's method dnd_leave(source, event), and then the new
target object's method dnd_enter(source, event) is called.
Once this is done, the new target object replaces the old one, and the
Tk mainloop proceeds. The return value of the methods mentioned above
is ignored; if they raise an exception, the normal exception handling
mechanisms take over.
The drag-and-drop processes can end in two ways: a final target object
is selected, or no final target object is selected. When a final
target object is selected, it will always have been notified of the
potential drop by a call to its dnd_enter() method, as described
above, and possibly one or more calls to its dnd_motion() method; its
dnd_leave() method has not been called since the last call to
dnd_enter(). The target is notified of the drop by a call to its
method dnd_commit(source, event).
If no final target object is selected, and there was an old target
object, its dnd_leave(source, event) method is called to complete the
dnd sequence.
Finally, the source object is notified that the drag-and-drop process
is over, by a call to source.dnd_end(target, event), specifying either
the selected target object, or None if no target object was selected.
The source object can use this to implement the commit action; this is
sometimes simpler than to do it in the target's dnd_commit(). The
target's dnd_commit() method could then simply be aliased to
dnd_leave().
At any time during a dnd sequence, the application can cancel the
sequence by calling the cancel() method on the object returned by
dnd_start(). This will call dnd_leave() if a target is currently
active; it will never call dnd_commit().
"""
import tkinter
# The factory function
def dnd_start(source, event):
h = DndHandler(source, event)
if h.root:
return h
else:
return None
# The class that does the work
class DndHandler:
root = None
def __init__(self, source, event):
if event.num > 5:
return
root = event.widget._root()
try:
root.__dnd
return # Don't start recursive dnd
except AttributeError:
root.__dnd = self
self.root = root
self.source = source
self.target = None
self.initial_button = button = event.num
self.initial_widget = widget = event.widget
self.release_pattern = "<B%d-ButtonRelease-%d>" % (button, button)
self.save_cursor = widget['cursor'] or ""
widget.bind(self.release_pattern, self.on_release)
widget.bind("<Motion>", self.on_motion)
widget['cursor'] = "hand2"
def __del__(self):
root = self.root
self.root = None
if root:
try:
del root.__dnd
except AttributeError:
pass
def on_motion(self, event):
x, y = event.x_root, event.y_root
target_widget = self.initial_widget.winfo_containing(x, y)
source = self.source
new_target = None
while target_widget:
try:
attr = target_widget.dnd_accept
except AttributeError:
pass
else:
new_target = attr(source, event)
if new_target:
break
target_widget = target_widget.master
old_target = self.target
if old_target is new_target:
if old_target:
old_target.dnd_motion(source, event)
else:
if old_target:
self.target = None
old_target.dnd_leave(source, event)
if new_target:
new_target.dnd_enter(source, event)
self.target = new_target
def on_release(self, event):
self.finish(event, 1)
def cancel(self, event=None):
self.finish(event, 0)
def finish(self, event, commit=0):
target = self.target
source = self.source
widget = self.initial_widget
root = self.root
try:
del root.__dnd
self.initial_widget.unbind(self.release_pattern)
self.initial_widget.unbind("<Motion>")
widget['cursor'] = self.save_cursor
self.target = self.source = self.initial_widget = self.root = None
if target:
if commit:
target.dnd_commit(source, event)
else:
target.dnd_leave(source, event)
finally:
source.dnd_end(target, event)
# ----------------------------------------------------------------------
# The rest is here for testing and demonstration purposes only!
class Icon:
def __init__(self, name):
self.name = name
self.canvas = self.label = self.id = None
def attach(self, canvas, x=10, y=10):
if canvas is self.canvas:
self.canvas.coords(self.id, x, y)
return
if self.canvas:
self.detach()
if not canvas:
return
label = tkinter.Label(canvas, text=self.name,
borderwidth=2, relief="raised")
id = canvas.create_window(x, y, window=label, anchor="nw")
self.canvas = canvas
self.label = label
self.id = id
label.bind("<ButtonPress>", self.press)
def detach(self):
canvas = self.canvas
if not canvas:
return
id = self.id
label = self.label
self.canvas = self.label = self.id = None
canvas.delete(id)
label.destroy()
def press(self, event):
if dnd_start(self, event):
# where the pointer is relative to the label widget:
self.x_off = event.x
self.y_off = event.y
# where the widget is relative to the canvas:
self.x_orig, self.y_orig = self.canvas.coords(self.id)
def move(self, event):
x, y = self.where(self.canvas, event)
self.canvas.coords(self.id, x, y)
def putback(self):
self.canvas.coords(self.id, self.x_orig, self.y_orig)
def where(self, canvas, event):
# where the corner of the canvas is relative to the screen:
x_org = canvas.winfo_rootx()
y_org = canvas.winfo_rooty()
# where the pointer is relative to the canvas widget:
x = event.x_root - x_org
y = event.y_root - y_org
# compensate for initial pointer offset
return x - self.x_off, y - self.y_off
def dnd_end(self, target, event):
pass
class Tester:
def __init__(self, root):
self.top = tkinter.Toplevel(root)
self.canvas = tkinter.Canvas(self.top, width=100, height=100)
self.canvas.pack(fill="both", expand=1)
self.canvas.dnd_accept = self.dnd_accept
def dnd_accept(self, source, event):
return self
def dnd_enter(self, source, event):
self.canvas.focus_set() # Show highlight border
x, y = source.where(self.canvas, event)
x1, y1, x2, y2 = source.canvas.bbox(source.id)
dx, dy = x2-x1, y2-y1
self.dndid = self.canvas.create_rectangle(x, y, x+dx, y+dy)
self.dnd_motion(source, event)
def dnd_motion(self, source, event):
x, y = source.where(self.canvas, event)
x1, y1, x2, y2 = self.canvas.bbox(self.dndid)
self.canvas.move(self.dndid, x-x1, y-y1)
def dnd_leave(self, source, event):
self.top.focus_set() # Hide highlight border
self.canvas.delete(self.dndid)
self.dndid = None
def dnd_commit(self, source, event):
self.dnd_leave(source, event)
x, y = source.where(self.canvas, event)
source.attach(self.canvas, x, y)
def test():
root = tkinter.Tk()
root.geometry("+1+1")
tkinter.Button(command=root.quit, text="Quit").pack()
t1 = Tester(root)
t1.top.geometry("+1+60")
t2 = Tester(root)
t2.top.geometry("+120+60")
t3 = Tester(root)
t3.top.geometry("+240+60")
i1 = Icon("ICON1")
i2 = Icon("ICON2")
i3 = Icon("ICON3")
i1.attach(t1.canvas)
i2.attach(t2.canvas)
i3.attach(t3.canvas)
root.mainloop()
if __name__ == '__main__':
test()

View File

@ -1,216 +0,0 @@
# Tkinter font wrapper
#
# written by Fredrik Lundh, February 1998
#
# FIXME: should add 'displayof' option where relevant (actual, families,
# measure, and metrics)
#
__version__ = "0.9"
import tkinter
# weight/slant
NORMAL = "normal"
ROMAN = "roman"
BOLD = "bold"
ITALIC = "italic"
def nametofont(name):
"""Given the name of a tk named font, returns a Font representation.
"""
return Font(name=name, exists=True)
class Font:
"""Represents a named font.
Constructor options are:
font -- font specifier (name, system font, or (family, size, style)-tuple)
name -- name to use for this font configuration (defaults to a unique name)
exists -- does a named font by this name already exist?
Creates a new named font if False, points to the existing font if True.
Raises _tkinter.TclError if the assertion is false.
the following are ignored if font is specified:
family -- font 'family', e.g. Courier, Times, Helvetica
size -- font size in points
weight -- font thickness: NORMAL, BOLD
slant -- font slant: ROMAN, ITALIC
underline -- font underlining: false (0), true (1)
overstrike -- font strikeout: false (0), true (1)
"""
def _set(self, kw):
options = []
for k, v in kw.items():
options.append("-"+k)
options.append(str(v))
return tuple(options)
def _get(self, args):
options = []
for k in args:
options.append("-"+k)
return tuple(options)
def _mkdict(self, args):
options = {}
for i in range(0, len(args), 2):
options[args[i][1:]] = args[i+1]
return options
def __init__(self, root=None, font=None, name=None, exists=False, **options):
if not root:
root = tkinter._default_root
if font:
# get actual settings corresponding to the given font
font = root.tk.splitlist(root.tk.call("font", "actual", font))
else:
font = self._set(options)
if not name:
name = "font" + str(id(self))
self.name = name
if exists:
self.delete_font = False
# confirm font exists
if self.name not in root.tk.call("font", "names"):
raise tkinter._tkinter.TclError, "named font %s does not already exist" % (self.name,)
# if font config info supplied, apply it
if font:
root.tk.call("font", "configure", self.name, *font)
else:
# create new font (raises TclError if the font exists)
root.tk.call("font", "create", self.name, *font)
self.delete_font = True
# backlinks!
self._root = root
self._split = root.tk.splitlist
self._call = root.tk.call
def __str__(self):
return self.name
def __eq__(self, other):
return self.name == other.name and isinstance(other, Font)
def __getitem__(self, key):
return self.cget(key)
def __setitem__(self, key, value):
self.configure(**{key: value})
def __del__(self):
try:
if self.delete_font:
self._call("font", "delete", self.name)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
pass
def copy(self):
"Return a distinct copy of the current font"
return Font(self._root, **self.actual())
def actual(self, option=None):
"Return actual font attributes"
if option:
return self._call("font", "actual", self.name, "-"+option)
else:
return self._mkdict(
self._split(self._call("font", "actual", self.name))
)
def cget(self, option):
"Get font attribute"
return self._call("font", "config", self.name, "-"+option)
def config(self, **options):
"Modify font attributes"
if options:
self._call("font", "config", self.name,
*self._set(options))
else:
return self._mkdict(
self._split(self._call("font", "config", self.name))
)
configure = config
def measure(self, text):
"Return text width"
return int(self._call("font", "measure", self.name, text))
def metrics(self, *options):
"""Return font metrics.
For best performance, create a dummy widget
using this font before calling this method."""
if options:
return int(
self._call("font", "metrics", self.name, self._get(options))
)
else:
res = self._split(self._call("font", "metrics", self.name))
options = {}
for i in range(0, len(res), 2):
options[res[i][1:]] = int(res[i+1])
return options
def families(root=None):
"Get font families (as a tuple)"
if not root:
root = tkinter._default_root
return root.tk.splitlist(root.tk.call("font", "families"))
def names(root=None):
"Get names of defined fonts (as a tuple)"
if not root:
root = tkinter._default_root
return root.tk.splitlist(root.tk.call("font", "names"))
# --------------------------------------------------------------------
# test stuff
if __name__ == "__main__":
root = tkinter.Tk()
# create a font
f = Font(family="times", size=30, weight=NORMAL)
print f.actual()
print f.actual("family")
print f.actual("weight")
print f.config()
print f.cget("family")
print f.cget("weight")
print names()
print f.measure("hello"), f.metrics("linespace")
print f.metrics()
f = Font(font=("Courier", 20, "bold"))
print f.measure("hello"), f.metrics("linespace")
w = tkinter.Label(root, text="Hello, world", font=f)
w.pack()
w = tkinter.Button(root, text="Quit!", command=root.destroy)
w.pack()
fb = Font(font=w["font"]).copy()
fb.config(weight=BOLD)
w.config(font=fb)
tkinter.mainloop()

View File

@ -1,132 +0,0 @@
# tk common message boxes
#
# this module provides an interface to the native message boxes
# available in Tk 4.2 and newer.
#
# written by Fredrik Lundh, May 1997
#
#
# options (all have default values):
#
# - default: which button to make default (one of the reply codes)
#
# - icon: which icon to display (see below)
#
# - message: the message to display
#
# - parent: which window to place the dialog on top of
#
# - title: dialog title
#
# - type: dialog type; that is, which buttons to display (see below)
#
from tkinter.commondialog import Dialog
#
# constants
# icons
ERROR = "error"
INFO = "info"
QUESTION = "question"
WARNING = "warning"
# types
ABORTRETRYIGNORE = "abortretryignore"
OK = "ok"
OKCANCEL = "okcancel"
RETRYCANCEL = "retrycancel"
YESNO = "yesno"
YESNOCANCEL = "yesnocancel"
# replies
ABORT = "abort"
RETRY = "retry"
IGNORE = "ignore"
OK = "ok"
CANCEL = "cancel"
YES = "yes"
NO = "no"
#
# message dialog class
class Message(Dialog):
"A message box"
command = "tk_messageBox"
#
# convenience stuff
# Rename _icon and _type options to allow overriding them in options
def _show(title=None, message=None, _icon=None, _type=None, **options):
if _icon and "icon" not in options: options["icon"] = _icon
if _type and "type" not in options: options["type"] = _type
if title: options["title"] = title
if message: options["message"] = message
res = Message(**options).show()
# In some Tcl installations, Tcl converts yes/no into a boolean
if isinstance(res, bool):
if res: return YES
return NO
return res
def showinfo(title=None, message=None, **options):
"Show an info message"
return _show(title, message, INFO, OK, **options)
def showwarning(title=None, message=None, **options):
"Show a warning message"
return _show(title, message, WARNING, OK, **options)
def showerror(title=None, message=None, **options):
"Show an error message"
return _show(title, message, ERROR, OK, **options)
def askquestion(title=None, message=None, **options):
"Ask a question"
return _show(title, message, QUESTION, YESNO, **options)
def askokcancel(title=None, message=None, **options):
"Ask if operation should proceed; return true if the answer is ok"
s = _show(title, message, QUESTION, OKCANCEL, **options)
return s == OK
def askyesno(title=None, message=None, **options):
"Ask a question; return true if the answer is yes"
s = _show(title, message, QUESTION, YESNO, **options)
return s == YES
def askyesnocancel(title=None, message=None, **options):
"Ask a question; return true if the answer is yes, None if cancelled."
s = _show(title, message, QUESTION, YESNOCANCEL, **options)
# s might be a Tcl index object, so convert it to a string
s = str(s)
if s == CANCEL:
return None
return s == YES
def askretrycancel(title=None, message=None, **options):
"Ask if operation should be retried; return true if the answer is yes"
s = _show(title, message, WARNING, RETRYCANCEL, **options)
return s == RETRY
# --------------------------------------------------------------------
# test stuff
if __name__ == "__main__":
print "info", showinfo("Spam", "Egg Information")
print "warning", showwarning("Spam", "Egg Warning")
print "error", showerror("Spam", "Egg Alert")
print "question", askquestion("Spam", "Question?")
print "proceed", askokcancel("Spam", "Proceed?")
print "yes/no", askyesno("Spam", "Got it?")
print "yes/no/cancel", askyesnocancel("Spam", "Want it?")
print "try again", askretrycancel("Spam", "Try again?")

View File

@ -1,43 +0,0 @@
# A ScrolledText widget feels like a text widget but also has a
# vertical scroll bar on its right. (Later, options may be added to
# add a horizontal bar as well, to make the bars disappear
# automatically when not needed, to move them to the other side of the
# window, etc.)
#
# Configuration options are passed to the Text widget.
# A Frame widget is inserted between the master and the text, to hold
# the Scrollbar widget.
# Most methods calls are inherited from the Text widget; Pack methods
# are redirected to the Frame widget however.
from tkinter import *
from tkinter import _cnfmerge
class ScrolledText(Text):
def __init__(self, master=None, cnf=None, **kw):
if cnf is None:
cnf = {}
if kw:
cnf = _cnfmerge((cnf, kw))
fcnf = {}
for k in cnf.keys():
if type(k) == ClassType or k == 'name':
fcnf[k] = cnf[k]
del cnf[k]
self.frame = Frame(master, **fcnf)
self.vbar = Scrollbar(self.frame, name='vbar')
self.vbar.pack(side=RIGHT, fill=Y)
cnf['name'] = 'text'
Text.__init__(self, self.frame, **cnf)
self.pack(side=LEFT, fill=BOTH, expand=1)
self['yscrollcommand'] = self.vbar.set
self.vbar['command'] = self.yview
# Copy geometry methods of self.frame -- hack!
methods = Pack.__dict__.keys()
methods = methods + Grid.__dict__.keys()
methods = methods + Place.__dict__.keys()
for m in methods:
if m[0] != '_' and m != 'config' and m != 'configure':
setattr(self, m, getattr(self.frame, m))

File diff suppressed because it is too large Load Diff

View File

@ -1,956 +0,0 @@
# LogoMation-like turtle graphics
"""
Turtle graphics is a popular way for introducing programming to
kids. It was part of the original Logo programming language developed
by Wally Feurzeig and Seymour Papert in 1966.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it
the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
the direction it is facing, drawing a line as it moves. Give it the
command turtle.left(25), and it rotates in-place 25 degrees clockwise.
By combining together these and similar commands, intricate shapes and
pictures can easily be drawn.
"""
from math import * # Also for export
from time import sleep
import tkinter
speeds = ['fastest', 'fast', 'normal', 'slow', 'slowest']
class Error(Exception):
pass
class RawPen:
def __init__(self, canvas):
self._canvas = canvas
self._items = []
self._tracing = 1
self._arrow = 0
self._delay = 10 # default delay for drawing
self._angle = 0.0
self.degrees()
self.reset()
def degrees(self, fullcircle=360.0):
""" Set angle measurement units to degrees.
Example:
>>> turtle.degrees()
"""
# Don't try to change _angle if it is 0, because
# _fullcircle might not be set, yet
if self._angle:
self._angle = (self._angle / self._fullcircle) * fullcircle
self._fullcircle = fullcircle
self._invradian = pi / (fullcircle * 0.5)
def radians(self):
""" Set the angle measurement units to radians.
Example:
>>> turtle.radians()
"""
self.degrees(2.0*pi)
def reset(self):
""" Clear the screen, re-center the pen, and set variables to
the default values.
Example:
>>> turtle.position()
[0.0, -22.0]
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
[0.0, 0.0]
>>> turtle.heading()
0.0
"""
canvas = self._canvas
self._canvas.update()
width = canvas.winfo_width()
height = canvas.winfo_height()
if width <= 1:
width = canvas['width']
if height <= 1:
height = canvas['height']
self._origin = float(width)/2.0, float(height)/2.0
self._position = self._origin
self._angle = 0.0
self._drawing = 1
self._width = 1
self._color = "black"
self._filling = 0
self._path = []
self.clear()
canvas._root().tkraise()
def clear(self):
""" Clear the screen. The turtle does not move.
Example:
>>> turtle.clear()
"""
self.fill(0)
canvas = self._canvas
items = self._items
self._items = []
for item in items:
canvas.delete(item)
self._delete_turtle()
self._draw_turtle()
def tracer(self, flag):
""" Set tracing on if flag is True, and off if it is False.
Tracing means line are drawn more slowly, with an
animation of an arrow along the line.
Example:
>>> turtle.tracer(False) # turns off Tracer
"""
self._tracing = flag
if not self._tracing:
self._delete_turtle()
self._draw_turtle()
def forward(self, distance):
""" Go forward distance steps.
Example:
>>> turtle.position()
[0.0, 0.0]
>>> turtle.forward(25)
>>> turtle.position()
[25.0, 0.0]
>>> turtle.forward(-75)
>>> turtle.position()
[-50.0, 0.0]
"""
x0, y0 = start = self._position
x1 = x0 + distance * cos(self._angle*self._invradian)
y1 = y0 - distance * sin(self._angle*self._invradian)
self._goto(x1, y1)
def backward(self, distance):
""" Go backwards distance steps.
The turtle's heading does not change.
Example:
>>> turtle.position()
[0.0, 0.0]
>>> turtle.backward(30)
>>> turtle.position()
[-30.0, 0.0]
"""
self.forward(-distance)
def left(self, angle):
""" Turn left angle units (units are by default degrees,
but can be set via the degrees() and radians() functions.)
When viewed from above, the turning happens in-place around
its front tip.
Example:
>>> turtle.heading()
22
>>> turtle.left(45)
>>> turtle.heading()
67.0
"""
self._angle = (self._angle + angle) % self._fullcircle
self._draw_turtle()
def right(self, angle):
""" Turn right angle units (units are by default degrees,
but can be set via the degrees() and radians() functions.)
When viewed from above, the turning happens in-place around
its front tip.
Example:
>>> turtle.heading()
22
>>> turtle.right(45)
>>> turtle.heading()
337.0
"""
self.left(-angle)
def up(self):
""" Pull the pen up -- no drawing when moving.
Example:
>>> turtle.up()
"""
self._drawing = 0
def down(self):
""" Put the pen down -- draw when moving.
Example:
>>> turtle.down()
"""
self._drawing = 1
def width(self, width):
""" Set the line to thickness to width.
Example:
>>> turtle.width(10)
"""
self._width = float(width)
def color(self, *args):
""" Set the pen color.
Three input formats are allowed:
color(s)
s is a Tk specification string, such as "red" or "yellow"
color((r, g, b))
*a tuple* of r, g, and b, which represent, an RGB color,
and each of r, g, and b are in the range [0..1]
color(r, g, b)
r, g, and b represent an RGB color, and each of r, g, and b
are in the range [0..1]
Example:
>>> turtle.color('brown')
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.color(tup)
>>> turtle.color(0, .5, 0)
"""
if not args:
raise Error, "no color arguments"
if len(args) == 1:
color = args[0]
if type(color) == type(""):
# Test the color first
try:
id = self._canvas.create_line(0, 0, 0, 0, fill=color)
except tkinter.TclError:
raise Error, "bad color string: %r" % (color,)
self._set_color(color)
return
try:
r, g, b = color
except:
raise Error, "bad color sequence: %r" % (color,)
else:
try:
r, g, b = args
except:
raise Error, "bad color arguments: %r" % (args,)
assert 0 <= r <= 1
assert 0 <= g <= 1
assert 0 <= b <= 1
x = 255.0
y = 0.5
self._set_color("#%02x%02x%02x" % (int(r*x+y), int(g*x+y), int(b*x+y)))
def _set_color(self,color):
self._color = color
self._draw_turtle()
def write(self, text, move=False):
""" Write text at the current pen position.
If move is true, the pen is moved to the bottom-right corner
of the text. By default, move is False.
Example:
>>> turtle.write('The race is on!')
>>> turtle.write('Home = (0, 0)', True)
"""
x, y = self._position
x = x-1 # correction -- calibrated for Windows
item = self._canvas.create_text(x, y,
text=str(text), anchor="sw",
fill=self._color)
self._items.append(item)
if move:
x0, y0, x1, y1 = self._canvas.bbox(item)
self._goto(x1, y1)
self._draw_turtle()
def fill(self, flag):
""" Call fill(1) before drawing the shape you
want to fill, and fill(0) when done.
Example:
>>> turtle.fill(1)
>>> turtle.forward(100)
>>> turtle.left(90)
>>> turtle.forward(100)
>>> turtle.left(90)
>>> turtle.forward(100)
>>> turtle.left(90)
>>> turtle.forward(100)
>>> turtle.fill(0)
"""
if self._filling:
path = tuple(self._path)
smooth = self._filling < 0
if len(path) > 2:
item = self._canvas._create('polygon', path,
{'fill': self._color,
'smooth': smooth})
self._items.append(item)
self._path = []
self._filling = flag
if flag:
self._path.append(self._position)
def begin_fill(self):
""" Called just before drawing a shape to be filled.
Must eventually be followed by a corresponding end_fill() call.
Otherwise it will be ignored.
Example:
>>> turtle.begin_fill()
>>> turtle.forward(100)
>>> turtle.left(90)
>>> turtle.forward(100)
>>> turtle.left(90)
>>> turtle.forward(100)
>>> turtle.left(90)
>>> turtle.forward(100)
>>> turtle.end_fill()
"""
self._path = [self._position]
self._filling = 1
def end_fill(self):
""" Called after drawing a shape to be filled.
Example:
>>> turtle.begin_fill()
>>> turtle.forward(100)
>>> turtle.left(90)
>>> turtle.forward(100)
>>> turtle.left(90)
>>> turtle.forward(100)
>>> turtle.left(90)
>>> turtle.forward(100)
>>> turtle.end_fill()
"""
self.fill(0)
def circle(self, radius, extent = None):
""" Draw a circle with given radius.
The center is radius units left of the turtle; extent
determines which part of the circle is drawn. If not given,
the entire circle is drawn.
If extent is not a full circle, one endpoint of the arc is the
current pen position. The arc is drawn in a counter clockwise
direction if radius is positive, otherwise in a clockwise
direction. In the process, the direction of the turtle is
changed by the amount of the extent.
>>> turtle.circle(50)
>>> turtle.circle(120, 180) # half a circle
"""
if extent is None:
extent = self._fullcircle
frac = abs(extent)/self._fullcircle
steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)
w = 1.0 * extent / steps
w2 = 0.5 * w
l = 2.0 * radius * sin(w2*self._invradian)
if radius < 0:
l, w, w2 = -l, -w, -w2
self.left(w2)
for i in range(steps):
self.forward(l)
self.left(w)
self.right(w2)
def heading(self):
""" Return the turtle's current heading.
Example:
>>> turtle.heading()
67.0
"""
return self._angle
def setheading(self, angle):
""" Set the turtle facing the given angle.
Here are some common directions in degrees:
0 - east
90 - north
180 - west
270 - south
Example:
>>> turtle.setheading(90)
>>> turtle.heading()
90
>>> turtle.setheading(128)
>>> turtle.heading()
128
"""
self._angle = angle
self._draw_turtle()
def window_width(self):
""" Returns the width of the turtle window.
Example:
>>> turtle.window_width()
640
"""
width = self._canvas.winfo_width()
if width <= 1: # the window isn't managed by a geometry manager
width = self._canvas['width']
return width
def window_height(self):
""" Return the height of the turtle window.
Example:
>>> turtle.window_height()
768
"""
height = self._canvas.winfo_height()
if height <= 1: # the window isn't managed by a geometry manager
height = self._canvas['height']
return height
def position(self):
""" Return the current (x, y) location of the turtle.
Example:
>>> turtle.position()
[0.0, 240.0]
"""
x0, y0 = self._origin
x1, y1 = self._position
return [x1-x0, -y1+y0]
def setx(self, xpos):
""" Set the turtle's x coordinate to be xpos.
Example:
>>> turtle.position()
[10.0, 240.0]
>>> turtle.setx(10)
>>> turtle.position()
[10.0, 240.0]
"""
x0, y0 = self._origin
x1, y1 = self._position
self._goto(x0+xpos, y1)
def sety(self, ypos):
""" Set the turtle's y coordinate to be ypos.
Example:
>>> turtle.position()
[0.0, 0.0]
>>> turtle.sety(-22)
>>> turtle.position()
[0.0, -22.0]
"""
x0, y0 = self._origin
x1, y1 = self._position
self._goto(x1, y0-ypos)
def towards(self, *args):
"""Returs the angle, which corresponds to the line
from turtle-position to point (x,y).
Argument can be two coordinates or one pair of coordinates
or a RawPen/Pen instance.
Example:
>>> turtle.position()
[10.0, 10.0]
>>> turtle.towards(0,0)
225.0
"""
if len(args) == 2:
x, y = args
else:
arg = args[0]
if isinstance(arg, RawPen):
x, y = arg.position()
else:
x, y = arg
x0, y0 = self.position()
dx = x - x0
dy = y - y0
return (atan2(dy,dx) / self._invradian) % self._fullcircle
def goto(self, *args):
""" Go to the given point.
If the pen is down, then a line will be drawn. The turtle's
orientation does not change.
Two input formats are accepted:
goto(x, y)
go to point (x, y)
goto((x, y))
go to point (x, y)
Example:
>>> turtle.position()
[0.0, 0.0]
>>> turtle.goto(50, -45)
>>> turtle.position()
[50.0, -45.0]
"""
if len(args) == 1:
try:
x, y = args[0]
except:
raise Error, "bad point argument: %r" % (args[0],)
else:
try:
x, y = args
except:
raise Error, "bad coordinates: %r" % (args[0],)
x0, y0 = self._origin
self._goto(x0+x, y0-y)
def _goto(self, x1, y1):
x0, y0 = self._position
self._position = map(float, (x1, y1))
if self._filling:
self._path.append(self._position)
if self._drawing:
if self._tracing:
dx = float(x1 - x0)
dy = float(y1 - y0)
distance = hypot(dx, dy)
nhops = int(distance)
item = self._canvas.create_line(x0, y0, x0, y0,
width=self._width,
capstyle="round",
fill=self._color)
try:
for i in range(1, 1+nhops):
x, y = x0 + dx*i/nhops, y0 + dy*i/nhops
self._canvas.coords(item, x0, y0, x, y)
self._draw_turtle((x,y))
self._canvas.update()
self._canvas.after(self._delay)
# in case nhops==0
self._canvas.coords(item, x0, y0, x1, y1)
self._canvas.itemconfigure(item, arrow="none")
except tkinter.TclError:
# Probably the window was closed!
return
else:
item = self._canvas.create_line(x0, y0, x1, y1,
width=self._width,
capstyle="round",
fill=self._color)
self._items.append(item)
self._draw_turtle()
def speed(self, speed):
""" Set the turtle's speed.
speed must one of these five strings:
'fastest' is a 0 ms delay
'fast' is a 5 ms delay
'normal' is a 10 ms delay
'slow' is a 15 ms delay
'slowest' is a 20 ms delay
Example:
>>> turtle.speed('slow')
"""
try:
speed = speed.strip().lower()
self._delay = speeds.index(speed) * 5
except:
raise ValueError("%r is not a valid speed. speed must be "
"one of %s" % (speed, speeds))
def delay(self, delay):
""" Set the drawing delay in milliseconds.
This is intended to allow finer control of the drawing speed
than the speed() method
Example:
>>> turtle.delay(15)
"""
if int(delay) < 0:
raise ValueError("delay must be greater than or equal to 0")
self._delay = int(delay)
def _draw_turtle(self, position=[]):
if not self._tracing:
self._canvas.update()
return
if position == []:
position = self._position
x,y = position
distance = 8
dx = distance * cos(self._angle*self._invradian)
dy = distance * sin(self._angle*self._invradian)
self._delete_turtle()
self._arrow = self._canvas.create_line(x-dx,y+dy,x,y,
width=self._width,
arrow="last",
capstyle="round",
fill=self._color)
self._canvas.update()
def _delete_turtle(self):
if self._arrow != 0:
self._canvas.delete(self._arrow)
self._arrow = 0
_root = None
_canvas = None
_pen = None
_width = 0.50 # 50% of window width
_height = 0.75 # 75% of window height
_startx = None
_starty = None
_title = "Turtle Graphics" # default title
class Pen(RawPen):
def __init__(self):
global _root, _canvas
if _root is None:
_root = tkinter.Tk()
_root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
_root.title(_title)
if _canvas is None:
# XXX Should have scroll bars
_canvas = tkinter.Canvas(_root, background="white")
_canvas.pack(expand=1, fill="both")
setup(width=_width, height= _height, startx=_startx, starty=_starty)
RawPen.__init__(self, _canvas)
def _destroy(self):
global _root, _canvas, _pen
root = self._canvas._root()
if root is _root:
_pen = None
_root = None
_canvas = None
root.destroy()
def _getpen():
global _pen
if not _pen:
_pen = Pen()
return _pen
class Turtle(Pen):
pass
"""For documentation of the following functions see
the RawPen methods with the same names
"""
def degrees(): _getpen().degrees()
def radians(): _getpen().radians()
def reset(): _getpen().reset()
def clear(): _getpen().clear()
def tracer(flag): _getpen().tracer(flag)
def forward(distance): _getpen().forward(distance)
def backward(distance): _getpen().backward(distance)
def left(angle): _getpen().left(angle)
def right(angle): _getpen().right(angle)
def up(): _getpen().up()
def down(): _getpen().down()
def width(width): _getpen().width(width)
def color(*args): _getpen().color(*args)
def write(arg, move=0): _getpen().write(arg, move)
def fill(flag): _getpen().fill(flag)
def begin_fill(): _getpen().begin_fill()
def end_fill(): _getpen().end_fill()
def circle(radius, extent=None): _getpen().circle(radius, extent)
def goto(*args): _getpen().goto(*args)
def heading(): return _getpen().heading()
def setheading(angle): _getpen().setheading(angle)
def position(): return _getpen().position()
def window_width(): return _getpen().window_width()
def window_height(): return _getpen().window_height()
def setx(xpos): _getpen().setx(xpos)
def sety(ypos): _getpen().sety(ypos)
def towards(*args): return _getpen().towards(*args)
def done(): _root.mainloop()
def delay(delay): return _getpen().delay(delay)
def speed(speed): return _getpen().speed(speed)
for methodname in dir(RawPen):
""" copies RawPen docstrings to module functions of same name """
if not methodname.startswith("_"):
eval(methodname).__doc__ = RawPen.__dict__[methodname].__doc__
def setup(**geometry):
""" Sets the size and position of the main window.
Keywords are width, height, startx and starty:
width: either a size in pixels or a fraction of the screen.
Default is 50% of screen.
height: either the height in pixels or a fraction of the screen.
Default is 75% of screen.
Setting either width or height to None before drawing will force
use of default geometry as in older versions of turtle.py
startx: starting position in pixels from the left edge of the screen.
Default is to center window. Setting startx to None is the default
and centers window horizontally on screen.
starty: starting position in pixels from the top edge of the screen.
Default is to center window. Setting starty to None is the default
and centers window vertically on screen.
Examples:
>>> setup (width=200, height=200, startx=0, starty=0)
sets window to 200x200 pixels, in upper left of screen
>>> setup(width=.75, height=0.5, startx=None, starty=None)
sets window to 75% of screen by 50% of screen and centers
>>> setup(width=None)
forces use of default geometry as in older versions of turtle.py
"""
global _width, _height, _startx, _starty
width = geometry.get('width',_width)
if width >= 0 or width is None:
_width = width
else:
raise ValueError, "width can not be less than 0"
height = geometry.get('height',_height)
if height >= 0 or height is None:
_height = height
else:
raise ValueError, "height can not be less than 0"
startx = geometry.get('startx', _startx)
if startx >= 0 or startx is None:
_startx = _startx
else:
raise ValueError, "startx can not be less than 0"
starty = geometry.get('starty', _starty)
if starty >= 0 or starty is None:
_starty = starty
else:
raise ValueError, "startx can not be less than 0"
if _root and _width and _height:
if 0 < _width <= 1:
_width = _root.winfo_screenwidth() * +width
if 0 < _height <= 1:
_height = _root.winfo_screenheight() * _height
# center window on screen
if _startx is None:
_startx = (_root.winfo_screenwidth() - _width) / 2
if _starty is None:
_starty = (_root.winfo_screenheight() - _height) / 2
_root.geometry("%dx%d+%d+%d" % (_width, _height, _startx, _starty))
def title(title):
"""Set the window title.
By default this is set to 'Turtle Graphics'
Example:
>>> title("My Window")
"""
global _title
_title = title
def demo():
reset()
tracer(1)
up()
backward(100)
down()
# draw 3 squares; the last filled
width(3)
for i in range(3):
if i == 2:
fill(1)
for j in range(4):
forward(20)
left(90)
if i == 2:
color("maroon")
fill(0)
up()
forward(30)
down()
width(1)
color("black")
# move out of the way
tracer(0)
up()
right(90)
forward(100)
right(90)
forward(100)
right(180)
down()
# some text
write("startstart", 1)
write("start", 1)
color("red")
# staircase
for i in range(5):
forward(20)
left(90)
forward(20)
right(90)
# filled staircase
fill(1)
for i in range(5):
forward(20)
left(90)
forward(20)
right(90)
fill(0)
tracer(1)
# more text
write("end")
def demo2():
# exercises some new and improved features
speed('fast')
width(3)
# draw a segmented half-circle
setheading(towards(0,0))
x,y = position()
r = (x**2+y**2)**.5/2.0
right(90)
pendown = True
for i in range(18):
if pendown:
up()
pendown = False
else:
down()
pendown = True
circle(r,10)
sleep(2)
reset()
left(90)
# draw a series of triangles
l = 10
color("green")
width(3)
left(180)
sp = 5
for i in range(-2,16):
if i > 0:
color(1.0-0.05*i,0,0.05*i)
fill(1)
color("green")
for j in range(3):
forward(l)
left(120)
l += 10
left(15)
if sp > 0:
sp = sp-1
speed(speeds[sp])
color(0.25,0,0.75)
fill(0)
# draw and fill a concave shape
left(120)
up()
forward(70)
right(30)
down()
color("red")
speed("fastest")
fill(1)
for i in range(4):
circle(50,90)
right(90)
forward(30)
right(90)
color("yellow")
fill(0)
left(90)
up()
forward(30)
down();
color("red")
# create a second turtle and make the original pursue and catch it
turtle=Turtle()
turtle.reset()
turtle.left(90)
turtle.speed('normal')
turtle.up()
turtle.goto(280,40)
turtle.left(24)
turtle.down()
turtle.speed('fast')
turtle.color("blue")
turtle.width(2)
speed('fastest')
# turn default turtle towards new turtle object
setheading(towards(turtle))
while ( abs(position()[0]-turtle.position()[0])>4 or
abs(position()[1]-turtle.position()[1])>4):
turtle.forward(3.5)
turtle.left(0.6)
# turn default turtle towards new turtle object
setheading(towards(turtle))
forward(4)
write("CAUGHT! ", move=True)
if __name__ == '__main__':
demo()
sleep(3)
demo2()
done()

View File

@ -57,11 +57,6 @@ Library
ctypes.util.find_library(name) now call this function when name is
'm' or 'c'.
- The Tkinter module has been made a package and renamed 'tkinter'.
All Tkinter-related modules (like Tix, ScrolledText, turtle etc.)
are now submodules of that package and have been renamed to conform
to PEP 8 standards.
- The repr module has been renamed 'reprlib'. The old name is now
deprecated.

View File

@ -377,7 +377,6 @@ rm -f mainpkg.files tools.files
%files tkinter
%defattr(-,root,root)
%{__prefix}/%{libdirname}/python%{libvers}/lib-tk
%{__prefix}/%{libdirname}/python%{libvers}/tkinter
%{__prefix}/%{libdirname}/python%{libvers}/lib-dynload/_tkinter.so*
%endif

View File

@ -180,7 +180,6 @@ Source: Lib\lib-old\*.*; DestDir: {app}\Lib\lib-old; CopyMode: alwaysoverwrite;
Source: Lib\xml\*.*; DestDir: {app}\Lib\xml; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
Source: Lib\hotshot\*.*; DestDir: {app}\Lib\hotshot; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
Source: Lib\test\*.*; DestDir: {app}\Lib\test; CopyMode: alwaysoverwrite; Components: test; Flags: recursesubdirs
Source: Lib\tkinter\*.py; DestDir: {app}\Lib\tkinter; CopyMode: alwaysoverwrite; Components: tk; Flags: recursesubdirs
Source: Lib\site-packages\README.txt; DestDir: {app}\Lib\site-packages; CopyMode: alwaysoverwrite; Components: main
@ -298,9 +297,6 @@ Name: {app}\Lib\lib-old; Type: dirifempty
Name: {app}\Lib\lib-tk\*.pyc; Type: files
Name: {app}\Lib\lib-tk\*.pyo; Type: files
Name: {app}\Lib\lib-tk; Type: dirifempty
Name: {app}\Lib\tkinter\*.pyc; Type: files
Name: {app}\Lib\tkinter\*.pyo; Type: files
Name: {app}\Lib\tkinter; Type: dirifempty
Name: {app}\Lib\test\*.pyc; Type: files
Name: {app}\Lib\test\*.pyo; Type: files
Name: {app}\Lib\test; Type: dirifempty

View File

@ -2047,14 +2047,6 @@ item: Install File
end
item: Remark
end
item: Install File
Source=..\lib\tkinter\*.py
Destination=%MAINDIR%\Lib\tkinter
Description=Tkinter related library modules
Flags=0000000000000010
end
item: Remark
end
item: Install File
Source=..\lib\logging\*.py
Destination=%MAINDIR%\Lib\logging

View File

@ -916,7 +916,7 @@ def add_files(db):
parent, dir = pydirs.pop()
if dir == ".svn" or dir.startswith("plat-"):
continue
elif dir in ["lib-tk", "tkinter", "idlelib", "Icons"]:
elif dir in ["lib-tk", "idlelib", "Icons"]:
if not have_tcl:
continue
tcltk.set_current()