Как сделать таблицу в tkinter

от admin

Как сделать таблицу в tkinter

Для отображения данных в виде таблицы параметру show предпочтительно передать значение «headings» (если надо отображать заголовки), либо » » (для таблицы без заголовков). Определим небольшую таблицу с тремя столбцами:

Здесь данные, которые будут отображаться в таблице, определены в виде списка people, который хранит набор кортежей. Каждый кортеж состоит из трех элементов. Условно будем считать, что первый элемент кортежа представляет имя пользователя, второй — возраст, а третий — электронный адрес. И эти данные нам надо отобразить в таблице:

Для отображения этих данных определяем три столбца: name, age и email в виде кортежа и передаем их параметру columns :

Далее нам надо настроить заголовки столбца с помощью метода heading() класса Treeview (по умолчанию столбцы не имеют никаких заголовков). Данный метод принимает ряд параметров:

Первый параметр указывает на имя столбца. В примере выше определяем также параметр text , который определяет текст заголовка

И последний момент — добавляем сами данные в таблицу с помощью метода insert() класса Treeview

Первый параметр — пустая строка «» указывает, что элемент добавляется как элемент верхнего уровня (то есть у него нет родительского элемента). Значение END указывает, что элемент добавляется в конец набора. И параметр values в качестве добавляемых данных устанавливает кортеж person.

В итоге мы получим следующую таблицу:

Настройка столбца

Вполне возможно, что изначальные настройки столбцов нас не устроят. Например, текст заголовка располагается по умолчанию по центру, а данные столбца выравниваются по левому краю. Кроме того, каждый столбец имеет некоторую начальную ширину, в следствие чего ширина виджета может оказаться больше ширины окна. Либо мы захотим как-то иначе настроить вид столбца.

Прежде всего мы можем настроить заголовки столбца с помощью метода heading() :

column : имя настраиваемого столбца

text : текст заголовка

image : картинка для заголовка

anchor : устанавливает выравнивание заголовка по определенному краю. Может принимать значения n, e, s, w, ne, nw, se, sw, c

command : функция, выполняемая при нажатии на заголовок

Для настройки столбца в целом применяется метод column() :

column : индекс настраиваемого столбца в формате «# номер_столбца»

width : ширина столбца

minwidth : минимальная ширина

anchor : устанавливает выравнивание заголовка по определенному краю. Может принимать значения n, e, s, w, ne, nw, se, sw, c

stretch : указывает, будет ли столбец растягиваться при растяжении контейнера. Если будет, то значение True , иначе значение False

Применим некоторые из этих параметров:

В данном случае для заголовков устанавливаем выравнивание по левому краю. Для столбцов запрещаем растяжение и устанавливаем ширину.

настройка столбцов в таблице в виджете Treeview в Tkinter и Python

При добавлении изображения оно помещается в правой части. Например, установка изображения для третьего столбца:

Creating a Tkinter Table

Creating a Tkinter Table

You can use the GUI as standalone or integrated applications in a wider variety of applications.

This tutorial shows how to create a Tkinter table in Python, and also, we will discuss an approach related to the Tkinter table in Python.

Use Entry Widget to Create Table in Tkinter

Tkinter helps create tables, but it does not provide a user interface for the table widget. You can create a table by repeatedly displaying entry widgets in rows and columns.

However, to make a table with six rows and four columns, we will have to use a for loop (see below).

We need to create an Entry widget within these loops by creating an Entry class object (see below).

Now, we need to set this intersection in the rows and columns. This can be done using a grid() method, in which we can pass row and column as arguments, such as below.

Now we can use the insert() method to insert data into the Entry widget (see below).

The insert() method takes two parameters, END and data . The End parameter is responsible for adding continuous data at the end of the previous data in the Entry() widget.

You will create the data parameter by yourself; it can be a list, Excel sheet or database.

This is a logical approach used in the system below using data from the list. In this code, we take a list containing 6 tuples, and each contains four values holding the Employee id , Name , City and Age .

So, we will have a table with 6 rows and 4 columns in each row. This program can also be used with an Excel sheet or database to display all data in a table format.

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

Python Tkinter Table Tutorial

In this Python Tkinter tutorial, we will learn How to create a Table in Python Tkinter and we will also cover different examples related to Tkinter Table. And, we will cover these topics.

  • Python Tkinter Table
  • Python Tkinter Table with Scrollbar
  • Python Tkinter Table Widget
  • Python Tkinter Table Input
  • Python Tkinter Table List
  • Python Tkinter Table Refresh
  • Python Tkinter Table Canvas
  • Python Tkinter Table Sort
  • Python Tkinter Editable Table

Table of Contents

Python Tkinter Table

In this section, we learn about the Python Tkinter table and we create a Tkinter table with the help of Treeview. Treeview refers to hierarchical representation.

The Tkinter.ttk module is used to drive a tree view and we use the tree view to make a table. A table is useful to display data or information that is visible in form of rows and columns.

Code:

  • In this code, we take mygame .column() to represent the columns in Python Tkinter Table.
  • mygame.heading() is used to display the headings in the Python Tkinter Table.
  • mygame.insert() is used to insert the values in the Python Tkinter Table.
  • ttk.Treeview() helps us to create a table.
  • ‘bg‘ is defining the background color with ‘#AC99F2’.

Output:

After running this example, we have the following output which shows the data in the form of rows and columns inside a table.

Python Tkinter Table

Python Tkinter Table with Scrollbar

In this section, we will cover How to create a python Tkinter table with scrollbars.

  • At times, the screen size is not enough to display the entire data. So to navigate around the data scrollbars are used.
  • There are two types of scrollbars:
    • Horizontal Scrollbar
    • Vertical Scrollbar
    1. Horizontal Scrollbar allows you to navigate in right and left directions.
    2. Vertical Scrollbar allows you to navigate in Up and down directions.

    There are two ways to implement a scrollbar. The first is to implement directly on the main window and the second way is to create a frame and put other widgets on the LEFT and scrollbar on the RIGHT.

    Source code :

    In this example, we have demonstrated horizontal and vertical scrollbars in Python Tkinter.

    In the above example, we are using game_scroll.pack(side=RIGHT,fill=Y) for horizontal scrollbar and game_scroll.pack(side= BOTTOM,fill=X) for the vertical scrollbar.

    Output:

    Python Tkinter Table with Scrollbar

    Python Tkinter Table Widget

    The table is a tabular representation of data in rows and column format.
    Python Tkinter does not have a specific Table widget using which we can create a table.

    Python Tkinter Table widget or Python Tk Table widget can be created using List, Pandas, or Treeview from the ttk package.

    Let us understand with the help of an example.

    Here is the output of the above example.

    Python Table Widget

    Python Tkinter Table Input

    In this section, we will learn how to create a table with input fields in Python Tkinter.

Похожие статьи