Как установить tkinter python

Как установить tkinter python

Как установить tkinter для Python

Я пытаюсь импортировать Tkinter. Однако я получаю ошибку о том, что Tkinter не был установлен:

ImportError: Нет модуля с именем _tkinter, пожалуйста, установите пакет python-tk.

Возможно, я мог бы установить его с помощью synaptic manager, однако мне пришлось бы устанавливать его на каждую машину, на которой я программирую. Можно ли добавить библиотеку Tkinter в мое рабочее пространство и ссылаться на нее оттуда?

Ответ 1

Установить Tkinter локально для использования с системным Python довольно сложно. Вы можете собрать его из исходников, но это обычно не лучшая идея с дистрибутивом, основанным на бинарных пакетах, который вы, очевидно, используете. Безопаснее будет apt-get install python-tk на вашей машине (машинах) ( р аботает в дистрибутивах, основанных на Debian, например, в Ubuntu; в других дистрибутивах обратитесь к вашему пакетному менеджеру и списку пакетов).

Ответ 2

Скачайте tcl и tk с http://www.tcl.tk/software/tcltk/download.html и установите их локально.

Это может показаться хлопотным, но файлы крошечные, и установка происходит очень быстро. Затем повторно запустите python setup.py build и python setup.py install в каталоге установки python, и все должно сработать. У меня сработало, и теперь я могу импортировать Tkinter и т. д. на свое усмотрение.

Ответ 3

В этом руководстве мы рассмотрим, как установить его на linux и использовать на примере.

Сначала проверьте, установлен ли у вас python, а также проверьте его версию.

$ python Python 2.7.9 (по умолчанию, Apr 2 2015, 15:33:21) [GCC 4.9.2] на linux2 Введите «help», «copyright», «credits» или «license» для получения дополнительной информации.

Если у вас нет python, установите его sudo apt-get install python.

Если вы хотите установить python 3, введите следующее. Если вы новичок, я бы рекомендовал установить python 2, а не python 3. Python 2 все еще очень популярен, и на нем создано много приложений. На ubuntu python2 все еще используется по умолчанию sudo apt-get install python3.

Наконец, установите Tkinter:

sudo apt-get install python-tk

Для python 3 версии:

sudo apt-get install python3-tk

Как его использовать. Теперь давайте проверим, хорошо ли работает Tkinter на этом небольшом примере. Откройте терминал и войдите в оболочку python.

Если python был установлен правильно, вы получите приглашение >>>. aman@vostro:

Python 2.7.9 (default, Apr 2 2015, 15:33:21)

Type «help», «copyright», «credits» or «license» for more information.

Теперь импортируйте модуль Tkinter. Он не выдаст никакой ошибки, если он импортирован правильно. ПРИМЕЧАНИЕ: убедитесь, что вы ввели Tkinter (не tkinter) в python2 и tkinter (не Tkinter) в python3.

Теперь, чтобы проверить, вы можете создать пустое окно с помощью Tkinter.

Ответ 4

Ситуация на macOS все еще немного сложная, но решаемая:

Ответ 5

Я думаю, вам нужно установить tkinter в каталог репозитория кода. Для li nu x (Ubuntu или debian) откройте терминал. Установите пакет tkinter, выполнив эту команду в терминале.

sudo apt-get install python-tk

После установки пакета python-tk на терминале создайте новый файл python. Назовите его filename.py. В первой строке файла filename.py импортируйте tkinter в python-файл.

Чтобы создать tkinter с различными полями, вы можете воспользоваться этим руководством. https://www.delftstack.com/tutorial/tkinter-tutorial/

Документацию по tkinter можно найти здесь:

Надеюсь, это поможет. Не забудьте определить, что вам нужно в графическом интерфейсе на tkinter, прежде чем реализовывать его. Нарисованные схемы того, как будет выглядеть графический интерфейс, помогут в кодировании графического интерфейса Tkinter.

Ответ 6

Вам нужно только импортировать его:

import tkinter as tk

Тогда вы будете использовать фразу tk, которая короче и проще. Кроме того, я предпочитаю использовать messagebox:

from tkinter import messagebox as msgbx

Вот некоторые способы, которые вы сможете использовать.

# создание нового окна

# отобразить всплывающее окно

msgbx.showinfo(«заголовок», «некоторый текст»)

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

Installing Tk

In this chapter, you’ll get Tk installed on your machine, verify it works, and then see a quick example of what a Tk program looks like.

Jump to Tk Install Instructions:

Though pretty much all macOS and Linux machines come with Tk installed already, it’s often an older version (typically 8.4.x or an early 8.5). You want to make sure you’ve got at least version 8.5 (preferably 8.6) to use the new widget set, so if that’s not already there, you’ll want to install the newer version.

You’ll need both Tk and bindings for the language you’re using it from. Sometimes these are bundled together, sometimes not. Though there are lots of ways to install Tk, often the easiest is to download and install one of the versions provided by ActiveState (www.activestate.com).

Users of recent Python versions can avoid this intermediate step. Starting with Python 3.7, the binary installers available at python.org now include everything you need to use Tk out of the box. If you’re using an earlier Python version, or want to compile it yourself, you’ll need to install Tcl/Tk on your system to do so. In this case, ActiveState’s distributions are still the recommended way to go.

Remember, this tutorial assumes you’re using Python 3, not Python 2. There are some significant differences between the two, including module naming, which is the first thing you’ll encounter when trying Tkinter.

ActiveState is a company that sells professional developer tools for dynamic languages. They also provide (for free) quality-controlled distributions of some of these languages, and happen to employ a number of core developers of these languages.

Installing Tk on macOS

Install Tk for Python (Tkinter) on macOS

The Easy Way

As noted, the easiest way to get Tk and Tkinter installed on your system is using Python’s binary installer, available at python.org. Thanks to work by Python core developer Ned Deily, binary installers starting with version 3.7 include Tcl and Tk.

Remember, we’re using Python 3.x here, not 2.x. As of this writing, the latest 3.9 installer (3.9.0rc1) includes Tk 8.6.8.

If, however, you’re compiling Python yourself, you’ll have more work to do. Read on.

Installing Tcl/Tk

The Tkinter module is included with core Python, of course, but you’ll need a version of Tcl/Tk on your system to compile it against. Do yourself a huge favor and get the most recent version.

Whatever you do, do not rely on the Tk versions included in macOS! Older versions included Tk 8.4.x. Even more recent macOS versions include an early 8.5 version (8.5.9, released in 2010), which has several serious bugs easily triggered by Tkinter.

While there are several ways to get Tcl and Tk onto your machine, the easiest and most recommended is to use the ActiveTcl distribution.

In your web browser, visit www.activestate.com/products/activetcl. Download ActiveTcl (as of this writing, it’s version 8.6.9). Make sure to download an 8.6.x version, not something older! Note that you will need to create an account with ActiveState (no cost) to download it. After it’s downloaded, run the installer to get Tcl and Tk loaded onto your machine.

If you’re a masochist and want to read about other Tcl/Tk options and variations and how they interact with Python, see the Mac Tcl/Tk page at python.org If you want to compile Tcl/Tk from its source, see www.tcl.tk.

Compiling Python

When compiling Python from source, you may need to tell it where to find the ActiveTcl (or other) distribution. Otherwise, it might not find any Tcl/Tk distribution (so Tkinter won’t work), or it could find the (ancient and broken) version of Tcl/Tk supplied with macOS.

The initial «%» is the Unix shell prompt; you don’t have to type it. The rest of it should all go on one line without adding line breaks.

If you have multiple versions of Tcl/Tk installed on your system (and in the same frameworks), you may need to check inside the framework to ensure the most recent version is marked as the current one. If not, you may need to adjust your paths to point to the specific version (i.e., Versions/8.x/ ) within each framework.

When everything is built, be sure to test it out. Start Python from your terminal, e.g.

This should give you the Python command prompt. From the prompt, enter these two commands:

This should pop up a small window; the first line at the top of the window should say, «This is Tcl/Tk version 8.6»; make sure it is not 8.4 or 8.5!

You can also get the exact version of Tcl/Tk that is being used with:

It should return something like ‘8.6.9’.

Verified install using ActiveTcl 8.6.9.8609.2 and Python 3.90rc1 source code from python.org on macOS 10.15.6.

Install Tk for Tcl on macOS

On macOS, the easiest way to get Tk 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. Note that you will need to create an account with ActiveState (no cost) to download it. Make sure you’re downloading an 8.6.x version, not an older version.

Run the installer to get everything loaded onto your machine. When you’re done, you’ll find a shiny new application called «Wish 8.6» inside the Utilities folder of your Applications folder. This is the «wish» shell, an application that includes both Tcl and Tk.

If you launch that application, you’ll see two windows popup (see below), one titled «Wish» which will contain your application, and the second titled «Console» which is where you can type in Tcl/Tk commands.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python
The Wish application running on macOS.

For convenient use from the Unix command line, you’ll also find a script installed as /usr/local/bin/wish8.6 which will launch the same application.

To verify the exact version of Tcl/Tk that you are running, from the Wish console type the following:

We want this to be returning something like ‘8.6.9’.

Verified install using ActiveTcl 8.6.9.8609.2 on macOS 10.15.6.

Install Tk for Ruby (Ruby/Tk) on macOS

While previous versions of macOS included both Ruby and Tk (albeit older 8.4 versions), since Snow Leopard this has no longer been the case.

Ruby/Tk 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 first download the latest 8.6.x Tcl/Tk version from ActiveState.

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. Note that you will need to create an account with ActiveState (no cost) to download it. Again, make sure you’re downloading an 8.6.x version.

Run the installer and everything will be loaded onto your machine.

Install Ruby

Next, you’ll want to install Ruby. There are multiple ways to do this, as explained at www.ruby-lang.org. One option is to use a package manager like Homebrew. Once it’s been installed (at /usr/local/bin/brew ) you can install Ruby from a command prompt (e.g. Terminal) via:

The initial «%» is the Unix shell prompt; you don’t have to type it.

Install Ruby/Tk

Next, you’ll need to download and install Ruby’s Tk module, which is packaged as a Ruby gem. To do so, from the command prompt, run:

To verify that everything worked, start up /usr/local/opt/ruby/bin/irb and type:

The first line should load Ruby/Tk; typically if there was a problem with finding Tcl/Tk it would show up here. The second line will return the version of Tk that you’re running, which should be something like «8.6.9».

Verified install using ActiveTcl 8.6.9.8609.2 and Ruby 2.7.1 via Homebrew on macOS 10.15.6.

Install Tk for Perl (Tkx) on macOS

For modern Tk programming using Perl, the «Tkx» module is highly recommended, and we’ll be using that here. It links against an existing but separate Tk library. So, to get the latest version of Tk for Perl, we’re going to have to do first download the latest 8.6.x Tcl/Tk version from ActiveState.

This tutorial used to rely on the ActivePerl distribution from ActiveState, which bundled a full Tcl/Tk installation, as well as the Tkx module. Unfortunately, as of this writing, there is not a macOS version of ActivePerl available.

Install ActiveTcl

The «ActiveTcl» distribution from ActiveState contains the latest Tk, as well as the latest version of Tcl (which Perl’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. Note that you will need to create an account with ActiveState (no cost) to download it. Again, make sure you’re downloading an 8.6.x version.

Run the installer and everything will be loaded onto your machine.

Install Perl

Next, you’ll want to install Perl. There are multiple ways to do this, as explained at www.perl.org. One option is to use a package manager like Homebrew. Once it’s been installed (at /usr/local/bin/brew ) you can install Ruby from a command prompt (e.g. Terminal) via:

The initial «%» is the Unix shell prompt; you don’t have to type it.

Install Tkx

Next, you’ll need to download and install Perl’s Tkx module. We can grab it from CPAN. Unfortunately, at present it will not install correctly due to errors in its tests. We can bypass the tests and install it anyway. To do so, from the command prompt, run:

To check that this worked, run this from the Unix command line:

This will return the version of Tcl/Tk that it found. It should be something like «8.6.9».

Verified install using ActiveTcl 8.6.9.8609.2 and Perl 5.32.0 via Homebrew on macOS 10.15.6.

Installing Tk on Windows

Install Tk for Python (Tkinter) on Windows

Tkinter (and, since Python 3.1, ttk, the interface to the newer themed widgets) is included in the Python standard library. We highly recommend installing Python using the standard binary distributions from python.org. These will automatically install Tcl/Tk, which of course, is needed by Tkinter.

If you’re instead building Python from source code, the Visual Studio projects included in the «PCbuild» directory can automatically fetch and compile Tcl/Tk on your system.

Once you’ve installed or compiled Python, test it out to make sure Tkinter works. From the Python prompt, enter these two commands:

This should pop up a small window; the first line at the top of the window should say, «This is Tcl/Tk version 8.6»; make sure it is not 8.4 or 8.5!

You can also get the exact version of Tcl/Tk that is being used with:

It should return something like ‘8.6.9’.

Verified using Python 3.9.0rc1 binary installer from python.org (containing Tcl/Tk 8.6.9) on Windows 10 version 1809.

Install Tk for Tcl on 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.6.x version. Note that you will need to create an account with ActiveState (no cost) to download it.

Run the installer, and follow along. You’ll end up with a fresh install of ActiveTcl, usually located in C:\ActiveTcl. From a command prompt, you should then be able to run a Tcl/Tk 8.6 shell via:

This should pop up a small window titled «wish», 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:

We want this to be returning something like ‘8.6.9’.

Type «exit» in the console window to exit. You may also want to add C:\ActiveTcl\bin to your PATH environment variable.

Verified install using ActiveTcl 8.6.9.8609-2 on Windows 10.

Install Tk for Ruby (Ruby/Tk) on Windows

Luckily, it is now only mildly painful, thanks to the good folks behind RubyInstaller for Windows.

The one-click installer used to include everything you needed to run Ruby/Tk, including the underlying Tcl/Tk libraries. Unfortunately, Tk was removed from the Ruby standard library (stdlib) in version 2.4, and made available as an external gem. RubyInstaller followed suit.

Install ActiveTcl

First, you’ll need to install Tcl/Tk.

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.6.x version. Note that you will need to create an account with ActiveState (no cost) to download it.

Run the installer, and follow along. You’ll end up with a fresh install of ActiveTcl in C:\ActiveTcl.

Install Ruby

Install Ruby/Tk

Next, you’ll need to download and install Ruby’s Tk module, which is packaged as a Ruby gem. To do so, open a command prompt and run:

The initial «%» is the Unix shell prompt; you don’t have to type it.

Tell Ruby Where to Find ActiveTcl

You’re not done yet. If you try to use Tk from Ruby, it will complain that it can’t find the underlying Tcl/Tk libraries. We’ll need to do a couple of things to fix that.

Second, the Tcl and Tk shared libraries will look for a bunch of initialization and other scripts which were installed as part of ActiveTcl. The best way to specify where to find them is to set the TCL_LIBRARY and TK_LIBRARY system environment variables.

This can be done in the Windows control panel (or search for «system environment variables» from the taskbar). In Windows 10, you’ll find a button labelled «Environment Variables. » in the «Advanced» tab of «System Properties». Add these system variables:

If you’re running a shell via command prompt you’ll need to restart it to see those new additions.

To verify the version of Tk, start up your newly installed copy of ‘irb’ (which would have been installed in C:\Ruby26\bin ), and type:

The first line should load Ruby/Tk. The second line will return the version of Tk that you’re running, which should be something like «8.6.9».

Verified install using ActiveTcl 8.6.9.8609-2, RubyInstaller Ruby+DevKit 2.6.6-1 on Windows 10 version 1809.

Install Tk for Perl (Tkx) on Windows

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.

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. Note that you will need to create an account with ActiveState (no cost) to download it.

Run the installer and everything will be loaded onto your machine. On our machine, perl.exe was installed at «C:\Perl64\bin»

To find out what version of Tk Perl and Tkx are using, run this from the Windows command prompt:

We want this to be returning something like «8.5.13».

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). Use a more recent version, and and verify that you do have Tk 8.5 or newer.

Verified install using ActivePerl 5.28 on Windows 10 version 1809.

Installing Tk on Linux

Install Tk for Python (Tkinter) on Linux/X11

Tkinter (and, since Python 3.1, ttk, the interface to the newer themed widgets) is included in the Python standard library. It relies on Tcl/Tk being installed on your system. Depending on how you install Python, this may not happen automatically.

Remember, we’re using Python 3.x here, not 2.x.

You have several different options to get Python and Tkinter onto your machine. We’ll show you two, using your distro’s package manager, or compiling from source.

Option 1. Your Linux Distribution’s Package Manager

However, after you’re done installing Python, you should verify that Tkinter works correctly. Start a Python shell (e.g., /usr/bin/python3 ) and verify the install (see below).

If you’re getting an error saying «No module named tkinter» (without the single quotes around the module name), you’re probably using Python 2. This tutorial assumes Python 3.

Sometimes Linux distributions separate out their Tkinter support into a separate package. That saves installing the Tcl/Tk libraries for people who are using Python but not Tkinter. If so, you’ll need to find and install this package, which will also ensure that appropriate versions of the Tcl/Tk libraries are installed on your system.

For example, running Ubuntu 20.04LTS, Python 3.8.2 is already installed. However, to use Tkinter, you need to install a separate package, named python3-tk :

In this case, that package provides Tcl/Tk 8.6.x libraries to be used with Python.

Option 2. Install Tcl/Tk and Compile the Standard Python Distribution

If you’d like to use the standard source distribution from python.org, you can certainly do that.

But to do so, you’ll need to get the Tcl and Tk include files and libraries loaded on your machine first. Again, while there are several ways to do that, the easiest is to download and install ActiveTcl.

Next, download the current Python 3.x source distribution from python.org, and unpack it. On your configure line, you’ll need to tell it how to find the version of Tcl/Tk you installed. Then build as usual:

Make sure to verify your install (see below).

Didn’t work? There may have been an error compiling Python’s tkinter code. To check, from the main Python source directory, try touch Modules/_tkinter.c (note the underscore) and then make to recompile it. Watch closely for error messages.

Verifying your Install

At the Python command prompt, enter these two commands:

This should pop up a small window; the first line at the top of the window should say, «This is Tcl/Tk version 8.6»; make sure it is not 8.4!

If it gives you an error when you try to import tkinter (e.g., «If this fails your Python may not be configured for Tk»), something hasn’t been set up correctly. If you compiled Python yourself, see above to check for compile errors.

You can also get the exact version of Tcl/Tk that is being used with:

It should return something like ‘8.6.9’.

Verified install using ActiveTcl 8.6.9.8609.2 and Python 3.90rc1 source code from python.org on Ubuntu 20.04LTS.

Install Tk for Tcl on Linux/X11

Using a Package Manager

Using ActiveTcl

Another option 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.6.x version. Note that you will need to create an account with ActiveState (no cost) to download it.

This should pop up a window titled «wish8.6». To verify the exact version of Tcl/Tk that you are running, from the Wish prompt (in the terminal window) type the following:

We want this to be returning something like ‘8.6.9’. Type a control-D at the prompt in the terminal window to exit. You may also want to add /opt/ActiveTcl-8.6/bin to your Unix path.

Verified install using ActiveTcl 8.6.9.8609.2 on Ubuntu 20.04LTS.

Install Tk for Ruby (Ruby/Tk) on Linux/X11

To get Ruby/Tk working on Linux, we’ll rely on your distribution’s package manager. The package names and commands shown here are for Ubuntu, and may be different on your system.

Because Ruby/Tk is an add-on gem, it needs to be compiled on your system. That means we’re going to need to install the development versions of the Tcl/Tk libraries ( tk8.6-dev ) as well as Ruby ( ruby2.7-dev plus ruby2.7 for the command-line tools like irb and gem ]). This will also ensure we have the necessary compilers, dependent libraries like X11, and so on.

The initial «%» is the Unix shell prompt; you don’t have to type it.

Finally, you can install the Ruby/Tk binding with:

To verify that everything worked, start up irb and type:

The first line should load Ruby/Tk; 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.6.10».

Verified install using tk8.6-dev 8.6.10-1, ruby2.7.0 on Ubuntu 20.04LTS.

Install Tk for Perl (Tkx) on Linux/X11

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.

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. Note that you will need to create an account with ActiveState (no cost) to download it.

Run the installer and everything will be loaded onto your machine, in e.g. /opt/ActivePerl-5.28.

To find out what version of Tk Perl and Tkx are using, run this from the command line:

We want this to be returning something like «8.5.13».

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). Use a more recent version, and and verify that you do have Tk 8.5 or newer.

Verified install using ActivePerl 5.28.1 on Ubuntu 20.04LTS.

The Obligatory First Program

To make sure that everything actually did work, let’s try to run a «Hello World» program in Tk. While for something this short, you could just type it in directly to the interpreter, instead use your favorite text editor to put it in a file.

Save this to a file named «hello.py». From a command prompt, type:

Couldn’t find hello.py? You might be looking in the wrong directory. Try providing the full path to hello.py.

Save this to a file named «hello.tcl». From the wish shell, type:

Couldn’t find hello.tcl? You might be looking in the wrong directory. You can either give the full path to hello.tcl, or use Tcl’s pwd and cd commands to see what directory you’re in, and change to a different one.

Save this to a file named «hello.rb». Start up [tk::inl «irb»], and from the command prompt, type:

Couldn’t find hello.rb? You might be looking in the wrong directory. You can either give the full path to hello.rb, or use Ruby’s Dir.pwd and Dir.chdir commands to see what directory you’re in, and change to a different one.

Note that there are two underscores between «ttk» and «button».

Save this to a file named «hello.pl». From a command prompt, type:

Couldn’t find hello.pl? You might be looking in the wrong directory. Try providing the full path to hello.pl.

Not working? Are you sure you’re using an 8.5 or newer version of Tcl/Tk? See the install chapter.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python
Our first program. Some work left to do before the IPO.

Spotted a mistake? Couldn’t find what you were looking for? Suggestions? Let me know!
If you’ve found this tutorial useful, please check out Modern Tkinter.

Работа с Tkinter в Python

Есть несколько способов взаимодействия с программой: через командную строку или через графический интерфейс. GUI – это настольное приложение, которое предоставляет пользовательский интерфейс, помогающий визуально взаимодействовать с компьютером или любым электронным устройством с помощью графических значков. Благодаря этому графический интерфейс расширяет круг пользователей нашего программного обеспечения.

Python предоставляет множество пакетов, таких как Kivy, PythonQt, wxPython, Tkinter и т.д. для создания графических интерфейсов. Среди этих популярных пакетов, поддерживаемых Python для создания приложений с графическим интерфейсом, – это Tkinter.

Tkinter в Python – это стандартная встроенная библиотека графического интерфейса пользователя, которая предоставляет пользователям объектно-ориентированный интерфейс для набора инструментов графического интерфейса пользователя Tk. Модуль Tkinter является наиболее предпочтительным интерфейсом для построения графического интерфейса для программистов из-за его простоты использования.

Программисты могут быстро создавать приложения с графическим интерфейсом, используя Tkinter. В этом руководстве мы будем использовать Tkinter для создания приложений с графическим интерфейсом.

Создание образца окна

Мы только что обсудили, что при использовании графического интерфейса пользователь взаимодействует с элементами интерфейса, которые называются «виджетами». Такие виджеты, как кнопки и флажки, позволяют пользователю взаимодействовать с программой. Другие виджеты, такие как окна и фреймы, используются в качестве контейнеров для размещения других виджетов. Tkinter легко доступен при стандартной установке Python 3+. Таким образом, пользователю не нужно беспокоиться об установке модуля. Пользователю нужно просто импортировать модуль, используя import tkinter.

Используя Tkinter, создать образец окна очень просто, независимо от используемой вами операционной системы. Мы можем быстро создать окно с помощью следующих строк кода.

После первого шага импорта пакета Tkinter следующим шагом будет создание виджета корневого окна для любого приложения. В интерфейсе должен быть только один виджет главного окна. Все остальные виджеты будут иметь более низкую иерархию, чем корневой. Следовательно, виджет главного корневого окна должен быть создан до создания других виджетов.

Как вы видите в приведенном выше коде, мы инициализируем корневой цикл `mainloop`. Это вызывает функцию mainloop(), которая вызывает бесконечный цикл главного корневого окна. Это окно будет ожидать любого взаимодействия с пользователем, пока не будет вызван их метод quit(), или в случае, если пользователь закроет окно. Приведенный выше код создает образец виджета Window следующим образом:

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Создание виджета метки

Теперь мы научились создавать виджет Windows. Затем давайте добавим простой виджет Label, который отображает образец текста в главном корневом окне. В приведенном ниже примере создается простой виджет метки. Мы можем создать ее, используя класс метки следующим образом:

label_widget = tkinter.Label (root_window, text = «Создайте свой собственный графический интерфейс с помощью Tkinter»)

Класс метки принимает 2 обязательных аргумента, а именно желаемый родительский виджет метки (т.е. root_window) и текст, который будет отображаться меткой. Затем мы можем установить положение метки с помощью функции сетки следующим образом:

Ниже приведен пример вывода, в котором отображается окно с только что созданной меткой.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Настройка виджета метки

Мы можем настроить размер шрифта метки, изменив стиль шрифта, как показано ниже:

label_widget = tkinter.Label (root_window, text = «Создайте свой собственный графический интерфейс с помощью Tkinter», font = («Arial Italic», 40))

Как видите, мы можем использовать параметр font для изменения размера шрифта виджетов.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Настройка заголовка и размера окна

Как видно из приведенного выше примера, размер окна очень мал. Мы можем установить размер по умолчанию, используя функцию геометрии, которая принимает ширину и высоту окна в качестве параметров (в пикселях).

Вышеупомянутая строка кода изменяет размер окна до указанных выше параметров.

Точно так же мы можем добавить заголовок к виджету окна, используя функцию заголовка. Например:

root_window.title («Tkinter tutorial»).

Давайте настроим размер и заголовок окна, добавив указанные выше 2 строки кода в наше существующее приложение.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Мы создали минимальный графический интерфейс с окном и виджетом метки с помощью Tkinter в мгновение ока.

Как pip или легко установить tkinter

мой холостой бросает ошибки, которые и говорит tkinter невозможно импортировать.

там, кажется, много имен пакетов летать вокруг для этого.

это и другие различные варианты с tkinter-pypy не работают.

10 ответов

Ну я вижу здесь два решения:

Tkinter (и, начиная с Python 3.1, ttk) включены во все стандартные дистрибутивы Python. Важно, чтобы вы использовали версию Python, поддерживающую Tk 8.5 или выше, и ttk. Мы рекомендуем установить дистрибутив «ActivePython» из ActiveState, который включает в себя все, что вы необходимость.

в вашем веб-браузере перейдите вActivestate.com, и следуйте по ссылкам, чтобы загрузить издание сообщества ActivePython для Windows. Убедитесь, что вы загружаете 3.1 или более новую версию, а не 2.X версии.

Это должно дать вам командную строку Python. В командной строке введите следующие две команды:

Это должно появиться небольшое окно; первая строка в верхней части окна должна сказать: «это Tcl / Tk версии 8.5»; убедитесь, что это не 8.4!

2) Удалите 64-битный Python и установите 32-битный Python.

библиотека Tkinter встроена в каждую установку Python. И поскольку вы находитесь в windows, я считаю, что вы установили python через двоичные файлы на своем веб-сайте?

если да, то, скорее всего, вы вводите команду неправильно. Должно быть:

import Tkinter as tk

обратите внимание на заглавную T в начале Tkinter.

import tkinter as tk

Если вы используете virtualenv, можно установить tkinter с помощью sudo apt-get install python-tk (вместо python2), sudo apt-get install python3-tk (python3), и он будет отлично работать в виртуальной среде

при установке python для Windows используйте стандартную опцию или установите все, что она просит. Я получил ошибку, потому что я снял выбор tcl.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

то же самое касается Python 3:

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Я решил ту же проблему, используя эти две команды 100%

Я публикую в качестве верхнего ответа requotes документацию, которую я не нашел полезной.

tkinter поставляется в комплекте с python install на windows, Если вы выберете его во время окна установки.

решение состоит в том, чтобы восстановить установку (через удаление GUI в порядке) и выбрать для установки tk на этот раз. В этом процессе может потребоваться указать или повторно загрузить двоичный файл. Загрузка непосредственно из activestate не работала для меня.

Это обычная проблема люди имеют на windows, как это легко не хотят устанавливать TCL / TK, если вы не знаете, что это такое, но Matplotlib и т.д. требуют этого.

Установить tkinter для Python

Я пытаюсь импортировать Tkinter. Тем не менее, я получаю сообщение об ошибке, указывающее, что Tkinter не был установлен:

ImportError: нет модуля с именем _tkinter, пожалуйста, установите пакет python-tk

Я мог бы, вероятно, установить его с помощью synaptic manager (могу ли я?), однако, мне пришлось бы установить его на каждой машине, на которой я программирую. Можно ли добавить библиотеку Tkinter в мое рабочее пространство и ссылаться на нее оттуда?

15 ответов

не очень легко установить Tkinter локально для использования с системным Python. Вы можете создать его из источников, но это обычно не лучшая идея с дистрибутивом на основе двоичного пакета, который вы, по-видимому, используете.

безопасность apt-get install python-tk на вашей машине(машинах). (Работает в дистрибутивах, производных от Debian, таких как Ubuntu; обратитесь к менеджеру пакетов и списку пакетов в других дистрибутивах.)

Если, как и я, у вас нет привилегий root в вашей сети из-за ваших замечательных друзей в I. S., и вы работаете в локальной установке, у вас могут возникнуть проблемы с вышеуказанными подходами.

Я потратил века на Google-но в конце концов, это легко.

загрузите tcl и tk из http://www.tcl.tk/software/tcltk/download.html и установите их локально тоже.

это может показаться болью, но файлы крошечные, и установка очень быстрая.

На самом деле, вам просто нужно использовать следующее, Чтобы установить tkinter для python3:

кроме того, для пользователей Fedora, используйте следующую команду:

Если вы используете Python 3, это может быть потому, что вы набираете Tkinter не tkinter

вам понадобится пакет и его зависимости.

поскольку вы упомянули synaptic, вы должны использовать систему на основе Debian. один из способов получить то, что вам нужно:

для пользователей Arch Linux это немного похоже на

Если вы используете RHEL, CentOS, Oracle Linux и т. д. Вы можете использовать Yum для установки модуля tkinter

tk-devel также должен быть установлен в моем случае

установите их и перестройте python

Fedora release 25 (двадцать пять)

это сработало для меня.

есть _tkinter и Tkinter-оба работают на Py 3.икс Но для безопасности-загрузите Loopy и измените корневой каталог python(если вы используете IDE, такую как PyCharms) в каталог установки Loopy. Вы получите эту библиотеку и многое другое.

если вы используете Python 3 затем вы должны установить следующим образом:

Tkinter для Python 2 ( python-tk ) отличается от Python 3 ‘ s ( python3-tk ).

ситуация на macOS по-прежнему сложно, но выполнимо:

Python.org настоятельно рекомендуем загрузить tkinter из ActiveState, а ты должны читать лицензия first (подсказка: не распространять или не нужна поддержка).

при открытии загрузки OS X 10.11 отклонила его, потому что не смогла найти мою квитанцию: «ActiveTcl-8.6.pkg не может быть открыт, потому что он из неопознанного разработчик.»

Я последовал за OSXDaily исправить с 2012 который предложил разрешить из любого места. Но OS X теперь добавила опцию «Открыть в любом случае», чтобы разрешить (например) Active-Tcl как один раз, а опция» Anywhere » получила тайм-аут.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

sudo apt-get python-tk

и если вы хотите обновить существующий пакет или Python в этом случае:-

sudo apt-получить обновление

sudo apt-get remove [имя пакета]#в этом случае python-tk

Tkinter-это модуль GUI для python. вы можете использовать его для создания приложений на основе GUI в python. Tkinter предоставляет несколько GUI виджетов, таких как кнопки,меню, полотно,текст,рамки,надписи и т. д. для разработки настольных приложений.Хотя Tkinter очень популярен и входит в состав windows, MacOSX install of python, есть также альтернативные варианты, такие как pyQt, wxPython.

в этом уроке мы рассмотрим, как установить его на Linux и использовать его на примере.

во-первых, проверить если у вас установлен python, а также проверьте его версию

откройте терминал и введите python. если он установлен, то он покажет информацию, такую как версия, справка. проверьте свою версию (моя версия python 2.7.9)

$ python Python 2.7.9 (по умолчанию, 2 апреля 2015, 15:33 :21) [GCC 4.9.2] на linux2 Введите «справка», «авторское право», «кредиты» или «лицензия» для получения дополнительной информации.

если у вас нет python, установите его sudo apt-get install питон

если вы хотите установить python 3, введите следующее. Если вы новичок, я бы рекомендовал python 2 вместо python 3. Python 2 по-прежнему очень популярен, и на нем сделано много приложений. На ubuntu python2 по-прежнему по умолчанию sudo apt-получить установить python3

Наконец, Установите Tkinter

теперь давайте проверим, хорошо ли работает Tkinter с этим маленьким пример

откройте терминал и войдите в свою оболочку python. питон

если python был установлен правильно, вы получите приглашение>>>. aman@vostro:

теперь импортируйте модуль Tkinter. он не покажет никакой ошибки, если он был импортирован правильно. Примечание: убедитесь, что вы вводите Tkinter (не tkinter) в python2 и tkinter (не Tkinter) в python3.

теперь, просто чтобы проверить, вы можете создать пустой окно с помощью Tkinter.

Установите tkinter для Python

Вероятно, я мог бы установить его с помощью Synaptic Manager (можно?), Однако мне пришлось бы устанавливать его на каждую машину, на которой я программирую. Можно ли добавить библиотеку Tkinter в мое рабочее пространство и ссылаться на нее оттуда?

Нелегко установить Tkinter локально для использования с предоставленным системой Python. Вы можете создать его из исходников, но обычно это не лучшая идея для дистрибутива на основе бинарных пакетов, который вы, очевидно, используете.

Это безопаснее apt-get install python-tk на вашей машине (машинах). (Работает с дистрибутивами, производными от Debian, например для Ubuntu; обратитесь к вашему менеджеру пакетов и списку пакетов в других дистрибутивах.)

На самом деле, вам просто нужно использовать следующее для установки tkinter для python3:

Кроме того, для пользователей Fedora используйте следующую команду:

Если, как и я, у вас нет привилегий суперпользователя в вашей сети из-за ваших замечательных друзей в IS, и вы работаете в локальной установке, у вас могут возникнуть проблемы с вышеуказанными подходами.

Загрузите tcl и tk с http://www.tcl.tk/software/tcltk/download.html и установите их также локально.

Это может показаться проблемой, но файлы крошечные и установка очень быстрая.

Если вы используете Python 3, это может быть потому, что вы печатаете Tkinter не tkinter

Для пользователей Arch Linux это немного похоже на

вам понадобится пакет и его зависимости.

так как вы упомянули synaptic, вы должны использовать систему на основе Debian. один способ получить то, что вам нужно:

Если вы используете RHEL, CentOS, Oracle Linux и т. Д. Вы можете использовать yum для установки модуля tkinter

tk-devel также должен быть установлен в моем случае

установить их и восстановить Python

для пользователя python3: установите пакет python3-tk, выполнив следующую команду sudo apt-get install python3-tk

Если вы используете, Python 3 то вы должны установить следующим образом:

Tkinter for Python 2 ( python-tk ) отличается от Python 3 ‘s ( python3-tk ).

Выпуск Fedora 25 (Двадцать пять)

Это сработало для меня.

Для Python 3.7 на Ubuntu я должен был использовать, sudo apt-get install python3.7-tk чтобы это работало

Когда загрузка началась, OS X 10.11 отклонила ее, потому что не смогла найти мою квитанцию: «ActiveTcl-8.6.pkg не может быть открыт, потому что она от неизвестного разработчика».

Я следовал за исправлением OSXDaily от 2012 года, которое предлагало разрешить откуда угодно. Но OS X теперь добавил опцию «Открыть в любом случае», чтобы разрешить (например) Active-Tcl в качестве однократного отключения, а опция «Везде» получила тайм-аут.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

В этом уроке мы увидим, как установить его на Linux и использовать его с примером.

Сначала проверьте, установлен ли у вас Python, а также проверьте его версию.

$ python Python 2.7.9 (по умолчанию, 2 апреля 2015 г., 15:33:21) [GCC 4.9.2] в linux2 Введите «помощь», «авторское право», «кредиты» или «лицензия» для получения дополнительной информации. Информация.

Если у вас нет python, установите его sudo apt-get install python

Если вы хотите установить Python 3, введите следующее. Если вы новичок, я бы порекомендовал python 2 вместо python 3. Python 2 по-прежнему очень популярен, и на нем создано много приложений. В Ubuntu Python2 по-прежнему используется по умолчанию. Sudo apt-get install python3

Наконец, установите Tkinter

Как это использовать

Теперь давайте проверим, хорошо ли работает Tkinter на этом небольшом примере.

откройте свой терминал и войдите в вашу оболочку python. питон

для python3 python3

Если Python был установлен правильно, вы получите приглашение >>>. aman @ vostro:

Теперь импортируем модуль Tkinter. он не будет отображать ошибки, если он был импортирован правильно. ПРИМЕЧАНИЕ. Убедитесь, что вы вводите Tkinter (не tkinter) в python2 и tkinter (не Tkinter) в python3.

Теперь просто для проверки вы можете создать пустое окно, используя Tkinter.

Как установить tkinter python

How to use Tkinter Designer

Before using Tkinter Designer, you’ll need to install Python.

Later in this guide, you will use the Package Installer for Python (pip), which may require you to add Python to your system PATH.

2. Install Tkinter Designer

pip install tkdesigner

To run Tkinter Designer from the source code, follow the instructions below.

Download the source files for Tkinter Designer by downloading it manually or using GIT.

git clone https://github.com/ParthJadhav/Tkinter-Designer.git

Change your working directory to Tkinter Designer.

Install the necessary dependencies by running

This will install all requirements and Tkinter Designer. Before you use Tkinter Designer you need to create a Figma File with the below instructions.

If you already have created a file then skip to Using Tkinter Designer Section.

3. Make a Figma Account

Formatting Your Figma Design [Top]

Naming is Important

Figma Element NameTkinter Element
ButtonButton
LineLine
TextName it anything
RectangleRectangle
TextAreaText Area
TextBoxEntry
ImageCanvas.Image()

The code generated by Tkinter Designer is based on the names of elements from your Figma design and, as such, you need to name your elements accordingly. In Figma, rename your elements by double-clicking them in the Layers panel.

First, create a Frame that will serve as your Tkinter Window.

Adding Images

Text (Normal Text)

Entry (Single-Line User Input)

Text Area (Multi-Line User Input)

Rectangle

Normal Button

Refer to this video if you face any problem

Refer to this video if you face any problem

Using Tkinter Designer [Top]

There are some inputs you’ll need to collect to be able to use the TKinter Designer.

1. Personal Access Token

2. Getting your File URL

Using the CLI is as simple as installing the package and running the CLI tool.

To use CLI from the source code you need to clone the repository and then follow the below instructions.

To run the generated GUI, cd into the directory you built it to (e.g. build/) and run it just as you would any Tkinter GUI.

Open Tkinter Designer before doing the following steps

The output files from Tkinter Designer will be placed in your chosen directory, inside a new folder called build. Congratulations, you have now created your Tkinter GUI using Tkinter Designer!

Elements not visible? Misplaced?

Button has an unintended gray background?

Window is larger than the screen?

Files not generating?

Библиотека Tkinter в Python

Tkinter – это пакет для Python, предназначенный для работы с библиотекой Tk. Библиотека Tk содержит компоненты графического интерфейса пользователя (graphical user interface – GUI), написанные на языке программирования Tcl.

Под графическим интерфейсом пользователя (GUI) подразумеваются все те окна, кнопки, текстовые поля для ввода, скроллеры, списки, радиокнопки, флажки и др., которые вы видите на экране, открывая то или иное приложение. Через них вы взаимодействуете с программой и управляете ею.

Все эти элементы интерфейса вместе называют виджетами (widgets). В Python мы можем создать виджеты с помощью библиотеки tkinter. Этапы разработки интерфейса с GUI следующие:

Подключение библиотеки

Как и любой модуль, tkinter в Python можно импортировать двумя способами: командами import tkinter или from tkinter import * (имя модуля пишется со строчной буквы).

Рекомендуется использовать второй способ, т.к. это позволит не указывать каждый раз имя модуля при обращении к объектам, которые в нем содержаться. Пример:

Создание главного окна

Объект окна верхнего уровня создается при обращении к классу Tk модуля tkinter. Переменную, связанную с объектом-окном принято называть root (но можно назвать и другим именем). Рассмотрим пример создания главного окна:

При запуске будет выведено:

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Если не установить геометрию окна, то размер окна будет подогнан под размер виджетов, содержащихся в окне.

Работа с виджетами

В библиотеки tkinter существует множества виджетов. Для примера рассмотрим виджет “Button”.

У класса Button есть обязательный параметр – объект, которому кнопка принадлежит (у нас это окно root). Полный список виджетов мы рассмотрим в следующих статьях. Пример создания кнопки:

У кнопки есть много свойств: надпись, цвет фона, размер и т.д. Например, добавим текст нашей кнопке:

Чтобы наша кнопка появилась в окне программы необходимо использовать метод pack(). Добавим в наше окно кнопку:

Если вы заметили, то при нажатии на кнопку ничего не происходит т.к. у нас нету события. Действия(алгоритм) часто оформляют в виде функции, а затем вызывают необходимым событием. Создадим функцию:

Для закрепления теоретического материала соберем все наши примеры в одну программу. Листинг:

Если запустить данную программу и нажать на кнопку, то в консоли появится строчка “Привет, программист!”.

Строчка root.mainloop() должна быть всегда в конце скрипта. Окно не появится, пока мы не вызовим метод mainloop().

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Знакомство с Tkinter:

Как установить tkinter python

Tkinter is a wrapper around a GUI toolkit called Tk. It’s usually used through a language called Tcl, but tkinter allows us to use Tcl and Tk through Python. This means that we can use Tcl’s libraries like Tk with Python without writing any Tcl code.

If you installed Python yourself you already have tkinter. If you are using Linux you probably don’t, but you can install tkinter with your distribution’s package manager. For example, you can use this command on Debian-based distributions, like Ubuntu and Mint:

That’s enough talking. Let’s do the classic Hello World program 🙂

Run this program like any other program. It should display a tiny window with the text Hello World! in it. I’m way too lazy to take screenshots, so here’s some ASCII art:

There are many things going on in this short code. Let’s go through it line by line.

The root window is the main window of our program. In this case, it’s the only window that our program creates. Tkinter starts Tcl when you create the root window.

Like most other GUI toolkits, Tk uses widgets. A widget is something that we see on the screen. Our program has two widgets. The root window is a widget, and this label is a widget. A label is a widget that just displays text.

This adds the label into the root window so we can see it.

Instead of using a label variable, you can also do this:

Anyway. let’s continue going through the lines of our example code.

The code before this takes usually just a fraction of a second to run, but this line of code runs until we close the window. It’s usually something between a few seconds and a few hours.

There is a Tcl library called Ttk, short for «themed tk». I’ll show you why you should use it instead of the non-Ttk code soon.

The tkinter.ttk module contains things for using Ttk with Python. Here is a tkinter program that displays two buttons that do nothing when they are clicked. One of the buttons is a Ttk button and the other isn’t.

The GUI looks like this on Windows 7:

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

The ttk button is the one that looks a lot better. Tk itself is very old, and its button widget is probably just as old, and it looks very old too. Ttk widgets look much better in general, and you should always use Ttk widgets. tl;dr: Use ttk.

If you already have some code that doesn’t use Ttk widgets, you just need to add from tkinter import ttk and then replace tkinter.SomeWidget with ttk.SomeWidget everywhere. Most things will work just fine.

Unfortunately writing Ttk code is kind of inconvenient because there’s no way to create a root window that uses Ttk. Some people just create a Tk root window and add things to that, e.g. like this:

GUIs like this look horrible on my Linux system.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

This is annoying, but keep in mind that you only need to do this once for each window; in a big project you typically have many widgets inside each window, and this extra boilerplate doesn’t annoy that much after all.

Here is a complete hello world program. It shouldn’t look too horrible on anyone’s system.

Tkinter and the >>> prompt

The >>> prompt is a great way to experiment with things. You can also experiment with tkinter on the >>> prompt, but unfortunately it doesn’t work that well on all platforms. Everything works great on Linux, but on Windows the root window is unresponsive when root.mainloop() is not running.

Try the hello world example on the >>> prompt, just type it there line by line. It’s really cool to see the widgets appearing on the screen as you type. If this works on your system, that’s great! If not, you can run root.update() regularly to make it display your changes.

If you try to print a tkinter widget, the results can be surprising.

Doing the same thing looks roughly like this on Python 3.5 and older:

We can also change the text after creating the label in a few different ways (we’ll find this useful later):

The config and configure methods do the same thing, only their names are different.

It’s also possible to get the text after setting it:

There are multiple different ways to do the same things, and you can mix them however you want. Personally I like to use initialization arguments and treat the widget as a dict, but you can do whatever you want.

You can also convert the label to a dict to see all of the options and their values:

, ‘cursor’: », ‘state’: ‘normal’, ‘image’: », ‘bd’:

, ‘font’: ‘TkDefaultFont’, ‘justify’: ‘center’, ‘height’: 0, ‘highlight color’: ‘#ffffff’, ‘wraplength’:

That’s a mess! Let’s use pprint.pprint:

If you are wondering what an option does you can just try it and see, or you can read the manual page (see below).

Tkinter is not documented very well, but there are many good manual pages about Tk written for Tcl users. Tcl and Python are two different languages, but Tk’s manual pages are easy to apply to tkinter code. You’ll find the manual pages useful later in this tutorial.

This tutorial contains links to the manual pages, like this ttk_label(3tk) link. There’s also a list of the manual pages.

If you are using Linux and you want to read the manual pages on a terminal, you can also install Tk’s manual pages using your package manager. For example, you can use this command on Debian-based distributions:

Then you can read the manual pages like this:

Учебник по Tkinter в Python – руководство и примеры

Python предоставляет стандартную библиотеку Tkinter для создания графического пользовательского интерфейса для настольных приложений.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Разработка настольных приложений с помощью python Tkinter – не сложная задача. Пустое окно верхнего уровня Tkinter можно создать, выполнив следующие действия:

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Виджеты

Существуют различные виджеты, такие как button, canvas, checkbutton, entry и т. д., которые используются для создания приложений с графическим интерфейсом пользователя Python.

ВиджетОписание
1ButtonВиджет кнопки используется для добавления различных типов кнопок в приложение Python.
2CanvasЭтот виджет используется для рисования на холсте в окне.
3CheckbuttonИспользуется для отображения кнопки-флажка в окне.
4EntryВиджет ввода используется для отображения однострочного текстового поля. Обычно он используется для принятия пользовательских значений.
5FrameЭтот виджет можно определить как контейнер, в который можно добавить и организовать другой виджет.
6LabelМетка – это текст, используемый для отображения некоторого сообщения или информации о других виджетах.
7ListBoxВиджет ListBox используется для отображения пользователю списка параметров.
8MenubuttonMenubutton используется для отображения пунктов меню пользователю.
9MenuОн используется для добавления пользователю пунктов меню.
10MessageВиджет сообщения используется для отображения окна сообщения пользователю.
11RadiobuttonРадиокнопка отличается от кнопки-флажка. Здесь пользователю предоставляются различные варианты, и пользователь может выбрать среди них только один вариант.
12ScaleИспользуется для предоставления пользователю ползунка.
13ScrollbarОн предоставляет пользователю полосу прокрутки, чтобы пользователь мог прокручивать окно вверх и вниз.
14TextОн отличается от Entry, поскольку предоставляет пользователю многострочное текстовое поле, чтобы пользователь мог писать текст и редактировать текст внутри него.
15ToplevelИспользуется для создания отдельного оконного контейнера.
16SpinboxЭто виджет ввода, используемый для выбора вариантов значений.
17PanedWindowПохож на виджет-контейнер, который содержит горизонтальные или вертикальные панели.
18LabelFrameLabelFrame – это виджет, который действует как контейнер.
19MessageBoxЭтот модуль используется для отображения окна сообщения в настольных приложениях.

Геометрия

Геометрия Tkinter определяет метод, с помощью которого виджеты отображаются на дисплее. Python Tkinter предоставляет следующие геометрические методы.

Давайте подробно обсудим каждый из них.

Метод Python Tkinter pack()

Метод pack() используется для организации виджета в блоке. Виджетами позиций, добавленными в приложение Python с помощью метода pack(), можно управлять с помощью различных параметров, указанных в вызове метода.

Однако элементов управления меньше, а виджеты обычно добавляются менее организованно.

Синтаксис использования pack() приведен ниже:

Список возможных параметров, которые можно передать в pack(), приведен ниже.

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Метод Python Tkinter grid()

Менеджер геометрии grid() организует виджеты в табличной форме. Мы можем указать строки и столбцы в качестве параметров при вызове метода. Мы также можем указать диапазон столбцов (ширину) или диапазон строк (высоту) виджета.

Это более организованный способ размещения виджетов в приложении Python. Синтаксис использования grid() приведен ниже:

Список возможных параметров, которые можно передать внутри метода grid():

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Метод Python Tkinter place()

Менеджер place() упорядочивает виджеты по определенным координатам x и y.

Список возможных вариантов приведен ниже:

Как установить tkinter python. Смотреть фото Как установить tkinter python. Смотреть картинку Как установить tkinter python. Картинка про Как установить tkinter python. Фото Как установить tkinter python

Прежде чем изучать Tkinter, вы должны иметь базовые знания Python. Наше руководство по Python Tkinter разработано, чтобы помочь новичкам и профессионалам.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *