воскресенье, 2 декабря 2012 г.

Tk. Установка Tk

В этой главе мы научимся устанавливать Tk на ваш компьютер, проверять его работу, и затем увидим быстрый пример того, как выглядит Tk программа.
Хотя почти все машины на Mac OS X и Linux идет уже с установленным Tk, это часто устаревшая версия (обычно 8.4.х). Вы должны убедиться, что имеете последнюю версию 8.5 для использования нового множества виджетов, так что если 8.5 еще не на вашем компьютере - нужно установить ее.
Хотя существует множество способов установить Tk, наилегчайший из них - загрузка и установка одно из версий, предоставляемых ActiveState (www.activestate.com).
ActiveState - это компания, которая продает профессиональные инструменты разработки для интерпретируемых языков программирования. Они также распространяют (бесплатно) проверяемые на качество дистрибутивы некоторых из этих языков, и бывает нанимают на работу некоторых ведущих разработчиков этих языков.

Установка Tk на Mac OS X

On На Mac OS X, наилегчайший способ получить Tk - установить "ActiveTcl" дистрибутив от ActiveState, который включает Tck, Tk, плюс несколько других дополняющих библиотек.

Зайдите в вашем браузере на www.activestate.com, и следуйте длинной ссылке на загрузку "Community Edition of ActiveTcl", доступным в бинарнике. Убедитесь, что загружаете версию 8.5.х, а не старую 8.4.х.
Запустите установщик, для загрузки всего этого на свою машину. Когда закончите, вы найдете блестящее новое приложение, называемое "Wish 8.5" внутри папки Utilities в папке приложений. Это оболочка "wish", которая включает в себя Tcl и Tk сразу.
If Если запустить приложение, вы увидите два окна, заголовком первого будет "Wish" и оно будет содержать ваше приложение, и второе окно с заголовком "Console", в котором вы можете набирать Tcl/Tk команды.

Приложение Wish, запущенное на Mac OS X.

For Для удобного использования из командной строки Unix, вы также найдете скрипт, установленный как /usr/local/bin/wish8.5, который запустит то же самое приложение.
Для проверки текущей версии Tcl/Tk, которую вы запустили, из консоли Wish наберите следующее:
% info patchlevel
Мы хотим, чтобы это выдало вам нечто вроде "8.5.10"
Протестирована установка ActiveTcl 8.5.10.1 на Mac OS X 10.7.1.
While previous versions of Mac OS X included both Ruby and Tk (albeit older 8.4 versions), since Snow Leopard this has no longer been the case.
RubyTk is a binding that links against an existing but separate Tk library. So, to get the latest version of Tk for Ruby, we're going to have to do two things, first download the latest 8.5.x Tcl/Tk version from ActiveState, and then compile (or re-compile) Ruby to use it.

Install ActiveTcl
The "ActiveTcl" distribution from ActiveState contains the latest Tk, as well as the latest version of Tcl (which Ruby's Tk bindings use internally to talk to Tk). In your web browser, go to www.activestate.com, and follow along the links to download the Community Edition of ActiveTcl, available as a universal binary. Again, make sure you're downloading an 8.5.x version, not an older 8.4.x version.
Run the installer and everything will be loaded onto your machine.

Compile Ruby
Make sure you've got Apple's developer tools (i.e. Xcode, which includes gcc and friends). Then if you haven't already got it, go to www.ruby-lang.org to download the latest stable (currently 1.9.x) version of Ruby.
Unpack it, and then from the Unix command line, run (note that the "configure" command should all be entered on one line, the <install-dir> should be replaced with the location you'd like your version of Ruby installed:
% ./configure --prefix=<install-dir>
    --with-arch=x86_64,i386
    --enable-pthread
    --enable-shared
% make && make install
To verify that everything worked, start up your newly compiled copy of 'irb', and type:
% require 'tk'
% Tk::TK_PATCHLEVEL
The first line should load RubyTk; typically if there was a problem with compiling it would show up here. The second line will return the version of Tk that you're running, which should be something like "8.5.10".
Протестирована установка ActiveTcl 8.5.10, Ruby 1.9.3-p0, на Mac OS X 10.7.2.
For modern Tk programming using Perl, the "Tkx" module is highly recommended, and we'll be using that here. The easiest way to get set up is to use the "ActivePerl" distribution from www.activestate.com.

Install ActivePerl >= 5.10
The "ActivePerl" distribution from ActiveState includes not only Perl, but also recent versions of Tk and Tcl (which Tkx uses internally to talk to Tk). In your web browser, go to www.activestate.com, and follow along the links to download the Community Edition of ActivePerl, available as a universal binary.
Run the installer and everything will be loaded onto your machine. Note that ActivePerl will be installed in /usr/local/ActivePerl-5.x (where 'x' is the actual version, e.g. '14').
To find out what version of Tk Perl and Tkx are using, run this from the Unix command line:
% /usr/local/ActivePerl-5.14/bin/perl -MTkx -e 'print Tkx::info("patchlevel");'
We want this to be returning something like "8.5.9".
Versions of ActivePerl prior to 5.10 (and some of the first 5.10 builds) included earlier versions of Tcl/Tk (8.4.x rather than 8.5.x). We therefore very highly recommend upgrading to at least ActivePerl 5.10, and verify that you do have Tk 8.5 or newer.
Протестирована установка ActivePerl 5.14.2 на Mac OS X 10.7.2.

Tkinter (и, начиная с Python 3.1, ttk) включены в стандартный дистрибутив Python. Это важно, используете ли вы версию Python поддерживающую Tk 8.5 или выше, и ttk.Мы советуем устанавливать  дистрибутив "ActivePython" от ActiveState, который включает все, что вам нужно.
Перейдите в браузере на www.activestate.com, и следуйте  ссылкам для загрузки "Community Edition of ActivePython" для Mac OS X. Убедитесь, что вы загружаете версию 3.1 или более новую версию, а не 2.х версию.
Распакуйте установщик (./install.sh), и следуйте ссылкам. Все завершится установкой свежей версией ActivePython, расположенной, например, в /Library/Frameworks, а также ссылки на файлы версий, расположенные в /ust/local/bin (например, 'python3.2' если вы загрузили ActivePython 3.2.x). Из окна Терминала вы должны быть в состоянии запустить оболочку Python через:
% /usr/local/bin/python3.2
Это должно запустить интерактивную оболочку Python. В интерактивном режиме введите 2 команды:
>>> import tkinter
>>> tkinter._test()

Это должно привести к появлению маленького окна; первая строка наверху его должна говорить "This is Tcl/Tk version 8.5", убедитесь, что это не 8.4!
Вы также можете узнать текущую версию Tcl/Tk, которая используется с помощью:
>>> tkinter.Tcl().eval('info patchlevel')
которая должна вернуть что-то вроде '8.5.10'.
Протестирована установка ActivePython 3.2.1.2 на Mac OS X 10.7.1.

Установка Tk на Windows

On Windows, the easiest way to get Tcl/Tk onto your machine is to install the "ActiveTcl" distribution from ActiveState, which includes Tcl, Tk, plus a number of other extension libraries.
In your web browser, go to www.activestate.com, and follow along the links to download the Community Edition of ActiveTcl for Windows. Make sure you're downloading an 8.5.x version, not an older 8.4.x version.
Run the installer, and follow along. You'll end up with a fresh install of ActiveTcl, usually located in C:\Tcl. From a DOS command prompt, or the Start Menu's "Run..." command, you should then be able to run a Tcl/Tk 8.5 shell via:
% C:\Tcl\bin\wish85
This should pop up a small window titled "wish85", which will contain your application. A second, larger window titled "Console" is where you can type in Tcl/Tk commands. To verify the exact version of Tcl/Tk that you are running, type the following:
% info patchlevel
We want this to be returning something like '8.5.10'.
Type "exit" in the console window to exit. You may also want to add C:\Tcl\bin to your PATH environment variable.
Verified install using ActiveTcl 8.5.10.1 on Windows 7.
RubyTk is the binding for Tk. Installing it on your Windows machine used to be pure hell, involving installing a separate version of Tcl/Tk, downloading a development environment like Visual Studio, downloading the Ruby source code, carefully compiling Ruby, ...
Luckily, it is (since July 2011) now remarkably easy, because the good RubyInstaller for Windows people now include Tk 8.5 as part of their excellent and easy to use installer. Thanks very much!
So all you'll need to do is download and run RubyInstaller, making sure to check the option in the installer to include Tcl/Tk support. This will install everything into the directory you choose, e.g. "C:\Ruby192".
To verify the version of Tk, start up your newly installed copy of 'irb' (which would have been installed in e.g. "C:\Ruby192\bin"), and type:
% require 'tk'
% Tk::TK_PATCHLEVEL
The first line should load RubyTk. The second line will return the version of Tk that you're running, which should be something like "8.5.10".
Протестирована установка RubyInstaller 1.9.2-p290 на Windows 7.
For modern Tk programming using Perl, the "Tkx" module is highly recommended, and we'll be using that here. The easiest way to get set up is to use the "ActivePerl" distribution from www.activestate.com.

Install ActivePerl >= 5.10

The "ActivePerl" distribution from ActiveState includes not only Perl, but also recent versions of Tk and Tcl (which Tkx uses internally to talk to Tk). In your web browser, go to www.activestate.com, and follow along the links to download the Community Edition of ActivePerl.
Run the installer and everything will be loaded onto your machine. On our machine, perl.exe was installed at "C:\perl in"
To find out what version of Tk Perl and Tkx are using, run this from the Windows command prompt:
% perl -MTkx -e "print Tkx::info("patchlevel");"
We want this to be returning something like "8.5.9".
Versions of ActivePerl prior to 5.10 (and some of the first 5.10 builds) included earlier versions of Tcl/Tk (8.4.x rather than 8.5.x). We therefore very highly recommendupgrading to at least ActivePerl 5.10, and verify that you do have Tk 8.5 or newer.
Протестирована установка ActivePerl 5.12.4 на Windows 7.

Tkinter (и, начиная с Python 3.1, ttk) включены в стандартный дистрибутив Python. Это важно, используете ли вы версию Python поддерживающую Tk 8.5 или выше, и ttk.Мы советуем устанавливать  дистрибутив "ActivePython" от ActiveState, который включает все, что вам нужно.
Перейдите в браузере на www.activestate.com, и следуйте  ссылкам для загрузки "Community Edition of ActivePython" для Windows. Убедитесь, что вы загружаете версию 3.1 или более новую версию, а не 2.х версию.
Run Запустите установщик и следуйте инструкциям. По окончанию установки ActivePython будет расположен, например, в C:\python32. Из командной строки Windows, или из пункта пуска "Выполнить", вам нужно уметь запускать командную оболочку Python через:
% C:\python32\python
Это должно запустить интерактивную оболочку Python. В интерактивном режиме введите 2 команды:
>>> import tkinter
>>> tkinter._test()
Это должно привести к появлению маленького окна; первая строка наверху его должна говорить "This is Tcl/Tk version 8.5", убедитесь, что это не 8.4!
Вы также можете узнать текущую версию Tcl/Tk, которая используется с помощью:
>>> tkinter.Tcl().eval('info patchlevel')
которая должна вернуть что-то вроде '8.5.9'.
Протестирована установка ActivePython 3.2.1.2 на Windows 7.

Установка Tk на Linux

While Linux distributions pretty much all come with Tcl/Tk installed, most include Tk 8.4.x, and we want to make sure to get an 8.5.x version. The easiest way to do this is to install the "ActiveTcl" distribution from ActiveState, which includes Tcl, Tk, plus a number of other extension libraries.
In your web browser, go to www.activestate.com, and follow along the links to download the Community Edition of ActiveTcl for Linux. Make sure you're downloading an 8.5.x version, not an older 8.4.x version.
Unpack it, and run the installer (install.sh), and follow along. You'll end up with a fresh install of ActiveTcl, located in /opt/ActiveTcl-8.5. You should then be able to run a Tcl/Tk 8.5 shell via:
% /opt/ActiveTcl-8.5/bin/wish8.5
This should pop up a window titled "wish8.5". To verify the exact version of Tcl/Tk that you are running, from the Wish prompt (in the terminal window) type the following:
 % info patchlevel
We want this to be returning something like '8.5.10'. Type a control-D at the prompt in the terminal window to exit. You may also want to add /opt/ActiveTcl-8.5/bin to your Unix path.
Протестирована установка ActiveTcl 8.5.10.1 на Ubuntu 11.04.
While Linux distributions pretty much all come with both Tk and Ruby installed, one of them (or the connection between them) is usually very out of date.
RubyTk is a binding that links against an existing but separate Tk library. So, to get the latest version of Tk for Ruby, we're going to have to do two things, first download the latest 8.5.x Tcl/Tk version from ActiveState, and then compile Ruby to use it.
And don't think you're going to get away with just doing an apt-get with one of the prebuilt Ruby packages, oh no. Even the RubyTk packages for the newest Ruby versions still tend to be built against Tk 8.4. It's not like Tk 8.5 hasn't been out of beta for (as of this writing) almost five years...
Install ActiveTcl
The "ActiveTcl" distribution from ActiveState contains the latest Tk, as well as the latest version of Tcl (which Ruby's Tk bindings use internally to talk to Tk). In your web browser, go to www.activestate.com, and follow along the links to download the Community Edition of ActiveTcl for Linux. Again, make sure you're downloading an 8.5.x version, not an older 8.4.x version.
Unpack it, and run the installer (install.sh), and follow along. You'll end up with a fresh install of ActiveTcl, located in /opt/ActiveTcl-8.5.

Setup your Development Environment
You'll need to make sure you have a fairly robust development environment on your machine. Besides the usual gcc and friends, make sure that you've got the X11 development files (e.g. all the include files; on Ubuntu there were included in the "libx11-dev" package).
Really, you need the X11 development files to compile, even though ActiveTcl is prebuilt and so doesn't need them. I wasted hours on this playing with various options, because the error messages if the headers aren't there are either missing or misleading.

Compile Ruby



Next, go to www.ruby-lang.org to download the latest stable (currently 1.9.x) version of Ruby.
Unpack it, and then from the Unix command line, run (note that the <install-dir> should be replaced with the location you'd like your version of Ruby installed):
% ./configure --prefix=<install-dir> && make && make install
This should locate the copy of ActiveTcl that you installed. To verify that everything worked, start up your newly compiled copy of 'irb', and type:
% require 'tk'
% Tk::TK_PATCHLEVEL
The first line should load RubyTk; typically if there was a problem with compiling it would show up here. The second line will return the version of Tk that you're running, which should be something like "8.5.10".
Протестирована установка ActiveTcl 8.5.10.1, Ruby 1.9.3-p0 на Ubuntu 11.04.
Для современного программирования Tk используя Perl, модуль Tkx настоятельно рекомендуем, и мы будем его использовать его здесь. Легчайший способ получить его - использовать дистрибутив ActivePerl, с www.activestate.com.

Установка ActivePerl >= 5.10
Дистрибутив "ActivePerl" от ActiveState включает не только Perl, но также последнюю версию Tk и Tcl (которую Tkx использует внутри для обращения к Tk). В вашем браузере перейдите на www.activestate.com, и следуйте ссылкам для загрузки "Community Edition of ActivePerl"
Запустите установщик и все загрузится на вашу машину, например в /opt/ActivePerl-5.12.
Для обнаружения используемой версии Tk Perl и Tkx, запустите это из командной строки:
% perl -MTkx -e 'print Tkx::info("patchlevel");'
что должно вернуть что-то вроде '8.5.9'.
Версии ActivePerl до 5.10 (и некоторые из первых сборок 5.10) содержат ранние версии Tcl/Tk (8.4.x чаще, чем 8.5.х). Поэтому мы настоятельно рекомендуем обновляться до последней ActivePerl 5.10, и проверять, что у вас Tk 8.5 или новее. Установка ActivePerl 5.12.4 на Ubuntu 11.04 протестирована.
Tkinter (и, начиная с Python 3.1, ttk) включены в стандартный дистрибутив Python. Это важно, используете ли вы версию Python поддерживающую Tk 8.5 или выше, и ttk.Мы советуем устанавливать  дистрибутив "ActivePython" от ActiveState, который включает все, что вам нужно.
Перейдите в браузере на www.activestate.com, и следуйте  ссылкам для загрузки "Community Edition of ActivePython" для Linux. Убедитесь, что вы загружаете версию 3.1 или более новую версию, а не 2.х версию.
Распакуйте установщик (./install.sh), и следуйте ссылкам. Все завершится установкой свежей версией ActivePython, расположенной, например, в /opt/ActivePython-3.2. Из окна Терминала вы должны быть в состоянии запустить оболочку Python через:
% /opt/ActivePython-3.2/bin/python3.2
Это должно запустить интерактивную оболочку Python. В интерактивном режиме введите 2 команды:
>>> import tkinter
>>> tkinter._test()
Это должно привести к появлению маленького окна; первая строка наверху его должна говорить "This is Tcl/Tk version 8.5", убедитесь, что это не 8.4!
Вы также можете узнать текущую версию Tcl/Tk, которая используется с помощью:
>>> tkinter.Tcl().eval('info patchlevel')
которая должна вернуть что-то вроде '8.5.9'.
Протестирована установка ActivePython 3.2.1.2 на Ubuntu 11.04