- Python — Tkinter Toplevel
- Syntax
- Parameters
- Methods
- Example
- Окна
- Удаление окна
- Определение окна в объектно-ориентированном стиле
- Окно поверх других окон
- Tkinter Toplevel
- Introduction to Tkinter Toplevel window
- A simple Tkinter Toplevel Window example
- Summary
- Python 3 — Tkinter Toplevel
- Syntax
- Parameters
- Methods
- Example
- Result
Python — Tkinter Toplevel
Toplevel widgets work as windows that are directly managed by the window manager. They do not necessarily have a parent widget on top of them.
Your application can use any number of top-level windows.
Syntax
Here is the simple syntax to create this widget −
Parameters
- options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
The background color of the window.
Border width in pixels; default is 0.
The cursor that appears when the mouse is in this window.
Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection=0 if you don’t want that behavior.
The default font for text inserted into the widget.
The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default.
Normally, a top-level window will have no 3-d borders around it. To get a shaded border, set the bd option larger that its default value of zero, and set the relief option to one of the constants.
The desired width of the window.
Methods
Toplevel objects have these methods −
Displays the window, after using either the iconify or the withdraw methods.
Returns a system-specific window identifier.
Adds the window to the window group administered by the given window.
Turns the window into an icon, without destroying it.
protocol(name, function)
Registers a function as a callback which will be called for the given protocol.
Turns the window into an icon, without destroying it.
Returns the current state of the window. Possible values are normal, iconic, withdrawn and icon.
Turns the window into a temporary(transient) window for the given master or to the window’s parent, when no argument is given.
Removes the window from the screen, without destroying it.
Defines the maximum size for this window.
Defines the minimum size for this window.
Defines the position controller.
resizable(width, height)
Defines the resize flags, which control whether the window can be resized.
Defines the size controller.
Example
Try following example yourself −
from Tkinter import * root = Tk() top = Toplevel() top.mainloop()
When the above code is executed, it produces the following result −
Окна
По умолчанию приложение Tkinter имеет одно главное окно, которое представляет класс tkinter.Tk . Запуск приложение приводит к запуску главного окно, в рамках которого помещаются все виджеты. Закрытие главного окна приводит к завершению работы приложения. Однако в рамках главного окна также можно запускать вторичные, неглавные окна. Например, октроем новое окно по нажатию на кнопку:
from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") def click(): window = Tk() window.title("Новое окно") window.geometry("250x200") button = ttk.Button(text="Создать окно", command=click) button.pack(anchor=CENTER, expand=1) root.mainloop()
Здесь по нажатию на кнопку создается новый объект window, у него устанавливается заголовок и размеры.
Стоит отметить, что приложение завершит работу, когда будут закрыты все его окна.
Как и главное окно, вторичные окна могут иметь виджеты. Например, определим на новом окне метку:
from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") def click(): window = Tk() window.title("Новое окно") window.geometry("250x200") label=ttk.Label(window, text="Принципиально новое окно") label.pack(anchor=CENTER, expand=1) button = ttk.Button(text="Создать окно", command=click) button.pack(anchor=CENTER, expand=1) root.mainloop()
Единственное не надо забывать у добавляемых виджетов устанавливать окно в качестве родительского контейнера
Удаление окна
Для удаления окна применяется меnод destroy()
from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") def click(): window = Tk() window.title("Новое окно") window.geometry("250x200") close_button = ttk.Button(window, text="Закрыть окно", command=lambda: window.destroy()) close_button.pack(anchor="center", expand=1) open_button = ttk.Button(text="Создать окно", command=click) open_button.pack(anchor="center", expand=1) root.mainloop()
В данном случае в новом окне по нажатию на кнопку close_button срабатывает метод window.destroy() , который закрывает окно и по сути аналогичен нажатию на крестик в верхнем правом углу окна.
Определение окна в объектно-ориентированном стиле
В примере выше новое окно, его параметры и вложенные виджеты определялись внутри функции, однако это приводит к разбуханию кода функции. И гораздо проще вынести определение окна в отдельный класс:
from tkinter import * from tkinter import ttk class Window(Tk): def __init__(self): super().__init__() # конфигурация окна self.title("Новое окно") self.geometry("250x200") # определение кнопки self.button = ttk.Button(self, text="закрыть") self.button["command"] = self.button_clicked self.button.pack(anchor="center", expand=1) def button_clicked(self): self.destroy() root = Tk() root.title("METANIT.COM") root.geometry("250x200") def click(): window = Window() open_button = ttk.Button(text="Создать окно", command=click) open_button.pack(anchor="center", expand=1) root.mainloop()
Здесь определение окна вынесено в отдельный класс Window, который наследуется от класса tkinter.Tk. Благодаря этому мы можем вынести весь код определения окна в отдельную структурную единицу — класс, что позволит упростить управление кодом.
Окно поверх других окон
Для создания диалогового окна, которое располагается поверх главного окна, применяется класс Toplevel :
from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") def dismiss(window): window.grab_release() window.destroy() def click(): window = Toplevel() window.title("Новое окно") window.geometry("250x200") window.protocol("WM_DELETE_WINDOW", lambda: dismiss(window)) # перехватываем нажатие на крестик close_button = ttk.Button(window, text="Закрыть окно", command=lambda: dismiss(window)) close_button.pack(anchor="center", expand=1) window.grab_set() # захватываем пользовательский ввод open_button = ttk.Button(text="Создать окно", command=click) open_button.pack(anchor="center", expand=1) root.mainloop()
Toplevel по сути то же самое окно Tk, которое располагается поверх других окон. В примере выше оно также имеет кнопку. Но кроме того, чтобы пользователь не мог перейти обратно к главному окну пока не закроет это диалоговое окно, применяется ряд методов. Прежде всего захватываем весь пользовательский ввод с помощью метода grab_set() :
В функции dismiss() , которая закрывает окно, освобождаем ввод с помощью метода grab_release()
Tkinter Toplevel
Summary: in this tutorial, you’ll learn how to create multiple windows in a Tkinter application using the Tkinter Toplevel class.
Introduction to Tkinter Toplevel window
In a Tkinter application, the instance of the Tk class represents the main window.
When you destroy the main window, the application exits, and the event loop finishes.
Sometimes, you need to create additional windows. For example, you may want to create a custom dialog or a wizard form.
To do that, you can use top-level windows which are instances of the Toplevel class.
Unlike the main window, you can create as many top-level windows as you want.
To show a Toplevel window from the main window, you follow these steps:
First, create an instance of the Toplevel class and set its parent to the root window:
window = tk.Toplevel(root)
Code language: Python (python)
The moment you create the Toplevel window, it’ll display on the screen.
Second, add widgets to the Toplevel window like you do with the frames and main window.
Third, call the grab_set() method of the Toplevel window instance to allow it to receive events and prevent users from interacting with the main window:
window.grab_set()
Code language: Python (python)
A simple Tkinter Toplevel Window example
The following program displays a window that has one button:
When you click the button, it’ll open a Toplevel window. The Toplevel window also consists of a button.
If you click or press the Close button, the Toplevel window closes.
import tkinter as tk from tkinter import ttk class Window(tk.Toplevel): def __init__(self, parent): super().__init__(parent) self.geometry('300x100') self.title('Toplevel Window') ttk.Button(self, text='Close', command=self.destroy).pack(expand=True) class App(tk.Tk): def __init__(self): super().__init__() self.geometry('300x200') self.title('Main Window') # place a button on the root window ttk.Button(self, text='Open a window', command=self.open_window).pack(expand=True) def open_window(self): window = Window(self) window.grab_set() if __name__ == "__main__": app = App() app.mainloop()
Code language: Python (python)
First, define a class Window that inherits from the Toplevel window. The Window will be closed once the Close button is clicked.
Second, assign the command of the Open a window button to the open_window() method in the App class
Third, in the open_window() method, create a new instance of the Window and call the grab_set() method so that it can receive events. The grab_set() method also prevents users from interacting with the main window.
Summary
- Show additional windows by creating instances of the Toplevel class.
- Use grab_set() method so that the Toplevel window can receive events and prevents users from interacting with the main window.
Python 3 — Tkinter Toplevel
Toplevel widgets work as windows that are directly managed by the window manager. They do not necessarily have a parent widget on top of them.
Your application can use any number of top-level windows.
Syntax
Here is the simple syntax to create this widget −
Parameters
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
The background color of the window.
Border width in pixels; default is 0.
The cursor that appears when the mouse is in this window.
Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection = 0 if you don’t want that behavior.
The default font for text inserted into the widget.
The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default.
Normally, a top-level window will have no 3-d borders around it. To get a shaded border, set the bd option larger that its default value of zero, and set the relief option to one of the constants.
The desired width of the window.
Methods
Toplevel objects have these methods −
Displays the window, after using either the iconify or the withdraw methods.
Returns a system-specific window identifier.
Adds the window to the window group administered by the given window.
Turns the window into an icon, without destroying it.
protocol(name, function)
Registers a function as a callback which will be called for the given protocol.
Turns the window into an icon, without destroying it.
Returns the current state of the window. Possible values are normal, iconic, withdrawn and icon.
Turns the window into a temporary(transient) window for the given master or to the window’s parent, when no argument is given.
Removes the window from the screen, without destroying it.
Defines the maximum size for this window.
Defines the minimum size for this window.
Defines the position controller.
resizable(width, height)
Defines the resize flags, which control whether the window can be resized.
Defines the size controller.
Example
Try following example yourself −
# !/usr/bin/python3 from tkinter import * root = Tk() root.title("hello") top = Toplevel() top.title("Python") top.mainloop()
Result
When the above code is executed, it produces the following result −