Как задать размер окна в tkinter

от admin

Как задать размер окна в tkinter

Основным компонентом графических программ является окно. Затем в окно добавляются все остальные компоненты графического интерфейса. В Tkinter окно представлено классом Tk . Например, создание окна:

Для отображения окна и взаимодействия с пользователем у окна вызывается метод mainloop()

Класс Tk обладает рядом методов и атрибутов, которые позволяют установить различные аспекты окна. Некоторые из них.

Размеры и начальная позиция окна

По умолчанию окно имеет некоторые стандартные размеры. Для установки размеров используется метод geometry() . Например, определение окна с шириной в 300 единиц и высотой 250 единиц:

По умолчанию окно позиционируется в верхний левый угол экрана с небольшим смещением. Но мы можем изменить его положение, передав нужные значения в метод geometry() :

Теперь строка в методе geometry имеет следующий формат: «Ширина x Высота + координатаX + координатаY». То есть при запуске окно шириной в 300 единиц и высотой 250 единиц будет находиться на 400 пикселей вправо и на 200 пикселей вниз от верхнего левого угла экрана.

Для получения данных о размере и позиции также можно использовать метод geometry() , который возвращает данные значения в виде строки в формате «widthxheight+x+y»:

Чтобы приложение еще до метода mainloop() принименило для окна переданные ему значения по ширине, высоте и позиции, вызывается метод root.update_idletasks() . В итоге вызов root.geometry() возвратить строку «300×250+400+200»

По умолчанию мы можем изменять размеры окна. Тем не менее иногда может потребоваться сделать размер окна фиксированным. В этом случае мы можем использовать метод resizable() . Его первый параметр указывает, может ли пользователь растягивать окно по ширине, а второй параметр — можно ли растягивать по высоте. Чтобы запретить растягивание по какой-либо стороне, необходимо для соответствующего параметра передать значение False . Например, запретим какое-либо изменение размеров:

Также можно установить минимальные и максимальные размеры окна:

Установка заголовка

По умолчанию заголовок окна — «tk». Для установки заголовка применяется метод title() , в который передается текст заголовка:

Установка иконки

Перед заголовком отображается иконка. По умолчанию это иконка пера. С помощью метода iconbitmap() можно задать любую другую иконку. Например, определим в одной папке с файлом приложения какой-нибудь файл с иконкой, допустип, он называется «favicon.ico» и используем его для установки иконки:

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

Иконка окна в thinkter в Python

В качестве альтернативы для установки иконки также можно было бы использовать метод iconphoto()

Первый параметр метода iconphoto() указывает, надо ли использовать иконку по умолчанию для всех окон приложения. Второй параметр — объект PhotoImage, который собственно и устанавливает файл изображения (здесь файл «icon2.png)

Однако что, если мы хотим, чтобы окно вообще не имело иконки? В этом случае можно определить прозрачную иконку и также ее подключать. Можно это сделать также динамически без наличия реального файла:

В данном случае создается временный файл иконки в памяти.

Перехват закрытия окна

Первый параметр метода protocol() представляет имя события, в данном случае это «WM_DELETE_WINDO». Второй параметр представляет функцию, которая вызывается при возникновении события. Здесь эта функция finish() , в котором с помощью метода destroy() вручную вызываем закрытие окна (а с ним и всего приложения), а затем выводим на консоль некоторое сообщение.

Атрибуты окна

С помощью специального метода attributes() можно установать отдельные атрибуты окна, для которых нет специальных методов. В качестве первого параметра метод принимает название атрибута, которое предваряется дефисом. А второй параметр — значение для этого атрибута. Например, растяжение окна на весь экран:

Здесь атрибуту fullscreen передается значение True, благодаря чему устанавливается полноэкранный режим.

Другой пример — установка прозрачности с помощью атрибута alpha :

Значение 0.5 указывает на полупрозрачность.

Третий пример — отключение верхней панели окна (за исключением заголовка и крестика для закрытия):

How to set the min and max height or width of a Frame?

The size of Tkinter windows can be controlled via the following methods:

Are there equivalent ways to control the size of Tkinter or ttk Frames?

@Bryan: I changed your frame1.pack code to the following:

And I added this event handler:

The above event handler detects that a frame’s width is too big, but is unable to prevent the increase in size from happening. Is this a limitation of Tkinter or have I misunderstood your explanation?

3 Answers 3

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn’t shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn’t shrink or expand to fit its own contents.

Note, however, that this won’t prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

A workaround — at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky=’nsew’. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don’t limit its minsize.

Читать:
Как обновить драйвера radeon software

Как установить окно Tkinter с постоянным размером

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

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

app.resizable(width=0, height=0) не позволяет изменять размер как ширину, так и высоту.

Установите фрейм Tkinter с постоянным размером

Рамка внутри окна немного похожа на окно, в том смысле, что она автоматически изменяет размер, даже если вы определяете ширину и высоту этой рамки.

Графический интерфейс, который мы ожидали, похож на приведенный ниже,

Но что мы получаем после выполнения вышеуказанных кодов, так это то,

Фрейм backFrame автоматически изменяет размер, чтобы подогнать под прикрепленные к нему виджеты. Другими словами, виджеты внутри backFrame контролируют размер своего родительского кадра.

Вы можете отключить изменение размера фрейма к его виджетам, установив pack_propagate(0) .

Tkinter Window

Summary: in this tutorial, you’ll learn how to manipulate various attributes of a Tkinter window.

Let’s start with a simple program that consists of a window:

The root window has a title that defaults to tk . It also has three system buttons including Minimize, Maximize, and Close.

Let’s learn how to change the attributes of the root window.

Changing the window title

To change the window’s title, you use the title() method like this:

For example, the following changes the title of the root window to ‘Tkinter Window Demo’ :

To get the current title of a window, you use the title() method with no argument:

Changing window size and location

In Tkinter, the position and size of a window on the screen is determined by geometry.

The following shows the geometry specification:

Tkinter Window Geometry

In this specification:

  • The width is the window’s width in pixels.
  • The height is the window’s height in pixels.
  • The x is the window’s horizontal position. For example, +50 means the left edge of the window should be 50 pixels from the left edge of the screen. And -50 means the right edge of the window should be 50 pixels from the right edge of the screen.
  • The y is the window’s vertical position. For example, +50 means the top edge of the window should be 50 pixels below the top of the screen. And -50 means the bottom edge of the window should be 50 pixels above the bottom of the screen.

To change the size and position of a window, you use the geometry() method:

The following example changes the size of the window to 600×400 and the position of the window to 50 pixels from the top and left of the screen:

Sometimes, you may want to center the window on the screen. The following program illustrates how to do it:

  • First, get the screen width and height using the winfo_screenwidth() and winfo_screenheight() methods.
  • Second, calculate the center coordinate based on the screen and window width and height.
  • Finally, set the geometry for the root window using the geometry() method.

If you want to get the current geometry of a window, you can use the geometry() method without providing any argument:

Resizing behavior

By default, you can resize the width and height of a window. To prevent the window from resizing, you can use the resizable() method:

The resizable() method has two parameters that specify whether the width and height of the window can be resizable.

The following shows how to make the window with a fixed size:

When a window is resizable, you can specify the minimum and maximum sizes using the minsize() and maxsize() methods:

Transparency

Tkinter allows you to specify the transparency of a window by setting its alpha channel ranging from 0.0 (fully transparent) to 1.0 (fully opaque):

The following example illustrates a window with 50% transparent:

Window stacking order

The window stack order refers to the order of windows placed on the screen from bottom to top. The closer window is on the top of the stack and it overlaps the one lower.

To ensure that a window is always at the top of the stacking order, you can use the -topmost attribute like this:

To move a window up or down of the stack, you can use the lift() and lower() methods:

The following example places the root window on top of all other windows. In other words, the root window is always on top:

Changing the default icon

Tkinter window displays a default icon. To change this default icon, you follow these steps:

  • Prepare an image in the .ico format. If you have the image in other formats like png or jpg , you can convert it to the .ico format. There are many online tools that allow you to do it quite easily.
  • Place the icon in a folder that can be accessible from the program.
  • Call the iconbitmap() method of the window object.

The following program illustrates how to change the default icon to a new one:

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