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

Окно графического прложения на Tkinter и Python, класс Tk, заголовок и иконка окна, установка размеров и позиции

Окно приложения

Последнее обновление: 10.09.2022

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

root = Tk()

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

from tkinter import *

root = Tk() 
root.mainloop()

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

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

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

from tkinter import *

root = Tk()
root.geometry("300x250")

root.mainloop()

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

from tkinter import *

root = Tk()
root.geometry("300x250+400+200")

root.mainloop()

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

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

from tkinter import * 

root = Tk()
root.geometry("300x250+400+200")

root.update_idletasks()
print(root.geometry())    # "300x250+400+200"

root.mainloop()

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

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

from tkinter import * 

root = Tk()
root.geometry("300x250")

root.resizable(False, False)

root.mainloop()

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

root.minsize(200,150)   # минимальные размеры: ширина - 200, высота - 150
root.maxsize(400,300)   # максимальные размеры: ширина - 400, высота - 300

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

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

from tkinter import * 

root = Tk()
root.title("Hello METANIT.COM")
root.geometry("300x250") 
root.mainloop()

Заголовок и размеры окна в thinkter в Python

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

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

from tkinter import * 

root = Tk()
root.title("Hello METANIT.COM")
root.iconbitmap(default="favicon.ico")
root.geometry("300x250") 
root.mainloop()

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

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

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

from tkinter import * 

root = Tk()
root.geometry("250x200")

root.title("Hello METANIT.COM")
icon = PhotoImage(file = "icon2.png")
root.iconphoto(False, icon)

root.mainloop()

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

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

from tkinter import *
import tempfile, base64, zlib

ICON = zlib.decompress(base64.b64decode("eJxjYGAEQgEBBiDJwZDBysAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc="))

_, ICON_PATH = tempfile.mkstemp()
with open(ICON_PATH, "wb") as icon_file:
    icon_file.write(ICON)

root = Tk()
root.title("Hello METANIT.COM")
root.geometry("300x250")

root.iconbitmap(default=ICON_PATH)

root.mainloop()

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

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

from tkinter import * 

def finish():
    root.destroy()  # ручное закрытие окна и всего приложения
    print("Закрытие приложения")

root = Tk()
root.geometry("250x200")

root.title("Hello METANIT.COM")
root.protocol("WM_DELETE_WINDOW", finish)

root.mainloop()

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

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

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

root.attributes("-fullscreen", True)

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

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

root.attributes("-alpha", 0.5)

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

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

root.attributes("-toolwindow", True)

Окна

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

Размер и положение окна

По умолчанию окно приложения появляется в верхнем левом углу экрана. Его размер (ширина и высота) определяется совокупностью размеров расположенных в нем виджетов. В случае если окно пустое, то tkinter устанавливает его размер в 200 на 200 пикселей.

С помощью метода geometry можно изменить как размер окна, так и его положение. Метод принимает строку определенного формата.

from tkinter import *
 
root = Tk()
 
root.geometry('600x400+200+100')
 
root.mainloop()

Первые два числа в строке-аргументе geometry задают ширину и высоту окна. Вторая пара чисел обозначает смещение на экране по осям x и y. В примере окно размерностью 600 на 400 будет смещено от верхней левой точки экрана на 200 пикселей вправо и на 100 пикселей вниз.

Если перед обоими смещениями вместо плюса указывается минус, то расчет происходит от нижних правых углов экрана и окна. Так выражение root.geometry('600x400-0-0') заставит окно появиться в нижнем правом углу.

В аргументе метода geometry можно не указывать либо размер, либо смещение. Например, чтобы сместить окно, но не менять его размер, следует написать root.geometry('+200+100').

Бывает удобно, чтобы окно появлялось в центре экрана. Методы winfo_screenwidth и winfo_screenheight возвращают количество пикселей экрана, на котором появляется окно. Рассмотрим, как поместить окно в центр, если размер окна известен:

…
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
w = w//2 # середина экрана
h = h//2 
w = w - 200 # смещение от середины
h = h - 200
root.geometry('400x400+{}+{}'.format(w, h))

Здесь мы вычитаем половину ширины и высоты окна (по 200 пикселей). Иначе в центре экрана окажется верхний левый угол окна, а не его середина.

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

from tkinter import *
root = Tk()
 
Button(text="Button", width=20).pack()
Label(text="Label", width=20, height=3).pack()
Button(text="Button", width=20).pack()
 
root.update_idletasks()
s = root.geometry()
s = s.split('+')
s = s[0].split('x')
width_root = int(s[0])
height_root = int(s[1])
 
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
w = w // 2
h = h // 2 
w = w - width_root // 2
h = h - height_root // 2
root.geometry('+{}+{}'.format(w, h))
 
root.mainloop()

Метод update_idletasks позволяет перезагрузить данные об окне после размещения на нем виджетов. Иначе geometry вернет строку, где ширина и высота равняются по одному пикселю. Видимо таковы параметры на момент запуска приложения.

По умолчанию пользователь может разворачивать окно на весь экран, а также изменять его размер, раздвигая границы. Эти возможности можно отключить с помощью метода resizable. Так root.resizable(False, False) запретит изменение размеров главного окна как по горизонтали, так и вертикали. Развернуть на весь экран его также будет невозможно, при этом соответствующая кнопка разворота исчезает.

Заголовок окна

По умолчанию с стоке заголовка окна находится надпись «tk». Для установки собственного названия используется метод title.

… 
root.title("Главное окно")

Если необходимо, заголовок окна можно вообще убрать. В программе ниже второе окно (Toplevel) открывается при клике на кнопку, оно не имеет заголовка, так как к нему был применен метод overrideredirect с аргументом True. Через пять секунд данное окно закрывается методом destroy.

from tkinter import *
 
 
def about():
    a = Toplevel()
    a.geometry('200x150')
    a['bg'] = 'grey'
    a.overrideredirect(True)
    Label(a, text="About this")
        .pack(expand=1)
    a.after(5000, lambda: a.destroy())
 
 
root = Tk()
root.title("Главное окно")
Button(text="Button", width=20).pack()
Label(text="Label", width=20, height=3)
    .pack()
Button(text="About", width=20, command=about)
    .pack()
 
root.mainloop()
 

Практическая работа

Напишите программу, в которой на главном окне находятся холст и кнопка «Добавить фигуру». Кнопка открывает второе окно, включающее четыре поля для ввода координат и две радиокнопки для выбора, рисовать ли на холсте прямоугольник или овал. Здесь же находится кнопка «Нарисовать», при клике на которую соответствующая фигура добавляется на холст, а второе окно закрывается. Проверку корректности ввода в поля можно опустить.

Курс с примерами решений практических работ:
pdf-версия,
android-приложение.

here is my one

  from tkinter import *
  import windll

  class CustomTitle():
        """
        Ex:
            root = Tk()
            titleBar = CustomTitle(root,title_text = 'Hello,World!' , bg = "#000000" , fg = '#ffffff')
            titleBar.resizeable = True
            titleBar.packBar()
            root.mainloop()
    
            Note:
                    Try to Give Color value in Hex and the 3rd car should be number
                        #7a4e7a
                           ↑ (this one)                  
        """
        resizeable = True
        font_style = ('Candara',13)
        
    
        def __init__(self,win,title_text='Custom Title Bar',bg='#ffffff',fg="#000000"):  
            # deactivating main title bar
            self._win = win
            win.title(title_text)
    
            # props
            self.bg = bg
            self._maximized = False
            self._win_width = win.winfo_width()
            self._win_height = win.winfo_height()
            self._scr_width = win.winfo_screenwidth()
            self._scr_height = win.winfo_screenheight()
            self._addWidget(title_text,bg,fg)
            
        def packBar(self):
            self._title_bar.pack(fill=X)
            self._checkAbility()
            self._win.overrideredirect(1)
            self._finilize()
    
        def _checkAbility(self):
            if not self.resizeable:
                self._maximize_btn.config(state=DISABLED)
            else:
                self._resizey_widget.pack(side=BOTTOM,ipadx=.1,fill=X)
                self._resizex_widget.pack(side=RIGHT,ipadx=.1,fill=Y)
    
        def _maximize_win(self):
            if not self._maximized:
                self._past_size = root.geometry()
                self._win.geometry(f"{self._scr_width}x{self._scr_height}+{0}+{0}")
                self._maximize_btn.config(text = '🗗')
            else:
                self._win.geometry(self._past_size)
                self._maximize_btn.config(text = '🗖')
            self._maximized = not self._maximized
    
    
        def _minimize(self):
            Minimize = win32gui.GetForegroundWindow()
            win32gui.ShowWindow(Minimize, win32con.SW_MINIMIZE)
    
        
        def _setIconToTaskBar(self,mainWindow):
            GWL_EXSTYLE = -20
            WS_EX_APPWINDOW = 0x00040000
            WS_EX_TOOLWINDOW = 0x00000080
            # Magic
            hwnd = windll.user32.GetParent(mainWindow.winfo_id())
            stylew = windll.user32.GetWindowLongW(hwnd, GWL_EXSTYLE)
            stylew = stylew & ~WS_EX_TOOLWINDOW
            stylew = stylew | WS_EX_APPWINDOW
            res = windll.user32.SetWindowLongW(hwnd, GWL_EXSTYLE, stylew)
        
            mainWindow.wm_withdraw()
            mainWindow.after(10, mainWindow.wm_deiconify)
    
        def _addWidget(self,title_text,bg,fg):
            self._title_bar = Frame(self._win,bd=1,bg=bg)
    
            self._title_text = Label(self._title_bar,text=title_text,bg=bg,fg=fg,font=self.font_style)
            self._title_text.pack(side=LEFT,padx=4,pady=3)
            self._title_text.bind("<B1-Motion>",self._drag)
    
            self._close_btn = Button(self._title_bar,text = '×',bd=0,bg=bg,fg=fg,width=3,font=self.font_style,command=self._win.destroy)
            self._close_btn.pack(side=RIGHT,fill=Y)
            self._maximize_btn = Button(self._title_bar,text="🗖",bd=0,bg=bg,fg=fg,width=3,font=self.font_style,command=self._maximize_win)
            self._maximize_btn.pack(side=RIGHT,fill=Y)
            self._minimize_btn = Button(self._title_bar,text="_",bd=0,bg=bg,fg=fg,width=3,font=self.font_style,command=self._minimize)
            self._minimize_btn.pack(side=RIGHT,fill=Y)
            self._title_bar.bind('<Button-1>', self._drag)
    
            self._resizex_widget = Frame(self._win,cursor='sb_h_double_arrow')
            self._resizex_widget.bind("<B1-Motion>",self._resizex)
    
            self._resizey_widget = Frame(self._win,cursor='sb_v_double_arrow')
            self._resizey_widget.bind("<B1-Motion>",self._resizey)
    
            self._hover_effect()
    
        def _hover_effect(self):
            try:
                num = int(self.bg[3]) - 1
                newbg = self.bg.replace(self.bg[3],str(num))
            except:
                newbg = "#c7ebe8"
    
            def change_bg(which_one,bg = newbg):
                which_one.config(bg=bg)
            def restore_bg(which_one):
                which_one.config(bg=self.bg)
            self._maximize_btn.bind('<Enter>',lambda event: change_bg(self._maximize_btn))
            self._maximize_btn.bind('<Leave>',lambda event: restore_bg(self._maximize_btn))
            self._minimize_btn.bind('<Enter>',lambda event: change_bg(self._minimize_btn))
            self._minimize_btn.bind('<Leave>',lambda event: restore_bg(self._minimize_btn))
            self._close_btn.bind('<Enter>',lambda event: change_bg(self._close_btn,bg='#db2730'))
            self._close_btn.bind('<Leave>',lambda event: restore_bg(self._close_btn))
    
    
        def _finilize(self):
            self._win.after(10, lambda: self._setIconToTaskBar(self._win))
    
        def _drag(self,event):
            xwin = root.winfo_x()
            ywin = root.winfo_y()
            startx = event.x_root
            starty = event.y_root
    
            ywin = ywin - starty
            xwin = xwin - startx
    
            def _move_window(event): # runs when window is dragged
    
                root.geometry(f'+{event.x_root + xwin}+{event.y_root + ywin}')
    
    
            def _release_window(event): # runs when window is released
                root.config(cursor="arrow")
                
            self._title_bar.bind('<B1-Motion>', _move_window)
            self._title_bar.bind('<ButtonRelease-1>', _release_window)
            self._title_text.bind('<B1-Motion>', _move_window)
            self._title_text.bind('<ButtonRelease-1>', _release_window)
    
    
        def _resizex(self,event):
    
            xwin = root.winfo_x()
    
            difference = (event.x_root - xwin) - root.winfo_width()
    
            if root.winfo_width() > 150 : # 150 is the minimum width for the window
                try:
                    root.geometry(f"{ root.winfo_width() + difference }x{ root.winfo_height() }")
                except:
                    pass
            else:
                if difference > 0: # so the window can't be too small (150x150)
                    try:
                        root.geometry(f"{ root.winfo_width() + difference }x{ root.winfo_height() }")
                    except:
                        pass
    
    
        def _resizey(self,event):
    
            ywin = root.winfo_y()
    
            difference = (event.y_root - ywin) - root.winfo_height()
    
            if root.winfo_height() > 150: # 150 is the minimum height for the window
                try:
                    root.geometry(f"{ root.winfo_width()  }x{ root.winfo_height() + difference}")
                except:
                    pass
            else:
                if difference > 0: # so the window can't be too small (150x150)
                    try:
                        root.geometry(f"{ root.winfo_width()  }x{ root.winfo_height() + difference}")
                    except:
                        pass

In this Python tutorial, we will learn everything about Python Tkinter Title. This blog is going to be an exploratory blog wherein we will answer the frequently asked questions. Also, we will cover these topics.

  • Python Tkinter title
  • How to change Python Tkinter title font size
  • Python Tkinter title bar color
  • Python Tkinter title bar text
  • Python Tkinter title center
  • Python Tkinter title color
  • Python Tkinter frame title
  • How to remove title bar in Python Tkinter

If you are new to Python TKinter or GUI programming, check out, Python GUI Programming.

  • Python Tkinter ‘title‘ refers to the name provided to the window. It appears on the top of the window & mostly found on the top left or center of the screen.
  • In the below picture you can notice that ‘PythonGuides’ is a title for the application.
  • It set the title of this widget
Python tkinter title
Python tkinter title

Syntax:

Here is the syntax of Python Tkinter ‘Title’.

wm_title(string=None)

Code Snippet:

Here is the simple code to create title of the window. ws.title('PythonGuides')

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')

ws.mainloop()

Output:

In this output, PythonGuides is displayed as the title of the screen. If you are windows you will see it on the left side of the window.

Python tkinter title
Python tkinter title

The above code we can use to set a title in Python Tkinter.

Read: Python Tkinter Autocomplete

Python tkinter title font size

  • Python Tkinter ‘Title’ does not allow to change the font size of the window. The solo purpose of ‘title’ is to provide a name or short description of the window.
  • This is a frequently asked question so we went through the official documentation & various other websites to find if there is any possibility to do that.
  • The official website provides no function to change the font size. Other websites are showing label as title.
  • This error we received while experimenting with font on the title.
Python tkinter title font size
Python tkinter title font size

Python tkinter title bar color

  • Title function offers one function that is to set a string on the top of the window. There is no official documentation to support the color implementation on the title bar.
  • Since this is a frequently asked question so we performed various experiments to discover tip for the user but none worked..
  • code on other website displays the placement & modification on widgets. They do no work on title bar that is on the top of the window.
  • type help(ws.title) to read the official documentation. Here ws is the name of the window.

Python tkinter title bar text

Title bar is used to set the name or description of the window. In this section we will learn how to set the title of the window in python tkinter.

Syntax:

Here is the syntax for adding title to the window.

ws.title(string=None)

Code Snippet:

Here is the code to add title to the application window.

from tkinter import *
ws = Tk()
ws.title('PythonGuides')

ws.mainloop()

Output:

Here is the output of the above code. You can notice ‘PythonGuides’ as the title.

Python tkinter title bar text
Python tkinter title bar text

Python tkinter title center

  • There is no official way of setting the title of application window to the center. But if you are a linux or mac os user then text will automatically appear in center of the title bar.
  • Windows user can apply some extra space to bring text to the center.

Python tkinter title color

  • Python tkinter title bar do not provide any option to set the color. Neither foreground color nor background color can be added.
  • Look and feel on Linux, Mac, and Windows may vary from each other.

Python Tkinter frame title

  • In this section, we will learn how to set title on the Tkinter frame. Also, we will share the common error messages & their fix.
  • Tkinter has provided two types of frame
    • Frame
    • LabelFrame
  • LabelFrame adds text or title to the window whereas Frame do not title to the frame window. Apart from this difference rest both have similar functionalities.
  • In case you are seeing error: _tkinter.TclError: unknown option "-text" that means you have used Frame instead of LabelFrame.
python tkinter frame error
Python Tkinter frame title

The right way of adding title to the frame is by using Label Frame. Here is the demonstration.

Code Snippet:

Here is the code snippet to add title on the LabelFrame. You can notice in the output ‘PythonGuides’ is the title for the frame.

from tkinter import *
ws = Tk()
ws.title(string='')
ws.geometry('400x300')

frame = LabelFrame(
    ws,
    text='PythonGuides',
    bg='#f0f0f0',
    font=(20)
)
frame.pack(expand=True, fill=BOTH)

Button(
    frame,
    text='Submit'
).pack()

ws.mainloop()

Output:

Here is the output of the above code snippet. You can notice there is PythonGuides written as the title of the frame.

python tkinter LabelFrame
Python Tkinter frame title

Python tkinter remove title bar

To remove title bar all you need to do is either delete the line ws.title(‘Any title’) or You can simply remove the text ‘Any title’. Here, any title is the title of the window.

You may like the following Python Tkinter tutorials:

  • How to Set Background to be an Image in Python Tkinter
  • Python Tkinter to Display Data in Textboxes
  • How to Create Countdown Timer using Python Tkinter
  • Upload a File in Python Tkinter
  • Python Tkinter drag and drop

In this tutorial, we have learned everything about Python Tkinter Title. Also, we have covered these topics.

  • python tkinter title
  • python tkinter title font size
  • python tkinter title bar color
  • python tkinter title bar text
  • python tkinter title center
  • python tkinter title color
  • python tkinter frame title
  • python tkinter remove title bar

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

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:

import tkinter as tk root = tk.Tk() root.mainloop()

Code language: Python (python)

Output:

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:

window.title(new_title)

Code language: Python (python)

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

import tkinter as tk root = tk.Tk() root.title('Tkinter Window Demo') root.mainloop()

Code language: Python (python)

Output:

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

title = window.title()

Code language: Python (python)

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:

widthxheight±x±y

Code language: Python (python)

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:

window.geometry(new_geometry)

Code language: Python (python)

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

import tkinter as tk root = tk.Tk() root.title('Tkinter Window Demo') root.geometry('600x400+50+50') root.mainloop()

Code language: Python (python)

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

import tkinter as tk root = tk.Tk() root.title('Tkinter Window - Center') window_width = 300 window_height = 200 # get the screen dimension screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() # find the center point center_x = int(screen_width/2 - window_width / 2) center_y = int(screen_height/2 - window_height / 2) # set the position of the window to the center of the screen root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}') root.mainloop()

Code language: PHP (php)

How it works.

  • 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:

window.geometry()

Code language: Python (python)

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:

window.resizable(width,height)

Code language: Python (python)

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:

import tkinter as tk root = tk.Tk() root.title('Tkinter Window Demo') root.geometry('600x400+50+50') root.resizable(False, False) root.mainloop()

Code language: Python (python)

Output:

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

window.minsize(min_width, min_height) window.maxsize(min_height, max_height)

Code language: Python (python)

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):

window.attributes('-alpha',0.5)

Code language: Python (python)

The following example illustrates a window with 50% transparent:

import tkinter as tk root = tk.Tk() root.title('Tkinter Window Demo') root.geometry('600x400+50+50') root.resizable(False, False) root.attributes('-alpha', 0.5) root.mainloop()

Code language: Python (python)

Output:

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:

window.attributes('-topmost', 1)

Code language: Python (python)

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

window.lift() window.lift(another_window) window.lower() window.lower(another_window)

Code language: Python (python)

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

import tkinter as tk root = tk.Tk() root.title('Tkinter Window Demo') root.geometry('300x200+50+50') root.resizable(0, 0) root.attributes('-topmost', 1) root.mainloop()

Code language: Python (python)

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:

import tkinter as tk root = tk.Tk() root.title('Tkinter Window Demo') root.geometry('300x200+50+50') root.resizable(FalseFalse) root.iconbitmap('./assets/pythontutorial.ico') root.mainloop()

Code language: PHP (php)

Output:

Tkinter window - customized icon

If you want to use the above icon, you can download it to your computer:

Summary

  • Use the title() method to change the title of the window.
  • Use the geometry() method to change the size and location of the window.
  • Use the resizable() method to specify whether a window can be resizable horizontally or vertically.
  • Use the window.attributes('-alpha',0.5) to set the transparency for the window.
  • Use the window.attributes('-topmost', 1) to make the window always on top.
  • Use lift() and lower() methods to move the window up and down of the window stacking order.
  • Use the iconbitmap() method to change the default icon of the window.

Did you find this tutorial helpful ?

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:

Блог веб разработки статьи | видеообзоры | исходный код

webfanat вконтактеwebfanat youtube

  • Главная /
  • PYTHON /
  • tkinter создание окна

tkinter создание окна

tkinter создание окна

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

Рассмотрим следующий код:

Здесь мы создали главное окно программы. Заметьте что оно имеет определенные размеры и заголовок Tk.

Допустим мы хотим чтобы наше главное окно имело заголовок ‘main’ и размеры 400×400.

Для этого в библиотеке tkinter существует метод title() который устанавливает заголовок и minize(), устанавливает ширину и высоту окна.

Для того чтобы окну задать определенный фон мы можем воспользоваться элементом frame:

здесь через класс Frame мы создали элемент frame.

В класс мы передали следующие аргументы:

window — объект главного окна

width и height — ширина и высота(совпадают с параметрами главного окна)

bg — цвет фона(green — зеленный)

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

Мы нарисовали флаг Российской Федерации в самом центре нашего главного окна используя виджет Frame. Помимо всего прочего мы можем в фрейм помещать другие элементы.

Например здесь мы текстовое поле поместили в frame2

И напоследок мы рассмотрим как создавать дополнительные(дочерние окна).

Дочерние окна создаются с помощью класса Toplevel которому передается в качестве аргумента объект главного окна.

В данном примере мы создали дополнительное окно с размерами 400×200 и заголовком ‘Дочернее окно’. Теперь мы можем обращаться и работать с ним через объект children. Отмечу что дочерних окон мы можем создавать сколько угодно.

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

На этом данная статья подошла к концу. Надеюсь она была для вас полезной.

Желаю удачи и успехов! Пока!

Оцените статью:
Статьи
Комментарии

Внимание. Комментарий теперь перед публикацией проходит модерацию

Все комментарии отправлены на модерацию

Реклама

Запись экрана

Данное расширение позволяет записывать экран и выводит видео в формате webm

Python Tkinter Title (Detailed Tutorial)

In this Python tutorial, we will learn everything about Python Tkinter Title. This blog is going to be an exploratory blog wherein we will answer the frequently asked questions. Also, we will cover these topics.

  • Python Tkinter title
  • How to change Python Tkinter title font size
  • Python Tkinter title bar color
  • Python Tkinter title bar text
  • Python Tkinter title center
  • Python Tkinter title color
  • Python Tkinter frame title
  • How to remove title bar in Python Tkinter

If you are new to Python TKinter or GUI programming, check out, Python GUI Programming.

Python Tkinter title

  • Python Tkinter ‘title‘ refers to the name provided to the window. It appears on the top of the window & mostly found on the top left or center of the screen.
  • In the below picture you can notice that ‘PythonGuides’ is a title for the application.
  • It set the title of this widget

Python tkinter title

Syntax:

Here is the syntax of Python Tkinter ‘Title’.

Code Snippet:

Here is the simple code to create title of the window. ws.title(‘PythonGuides’)

Output:

In this output, PythonGuides is displayed as the title of the screen. If you are windows you will see it on the left side of the window.

Python tkinter title

The above code we can use to set a title in Python Tkinter.

Python tkinter title font size

  • Python Tkinter ‘Title’ does not allow to change the font size of the window. The solo purpose of ‘title’ is to provide a name or short description of the window.
  • This is a frequently asked question so we went through the official documentation & various other websites to find if there is any possibility to do that.
  • The official website provides no function to change the font size. Other websites are showing label as title.
  • This error we received while experimenting with font on the title.

Python tkinter title font size

Python tkinter title bar color

  • Title function offers one function that is to set a string on the top of the window. There is no official documentation to support the color implementation on the title bar.
  • Since this is a frequently asked question so we performed various experiments to discover tip for the user but none worked..
  • code on other website displays the placement & modification on widgets. They do no work on title bar that is on the top of the window.
  • type help(ws.title) to read the official documentation. Here ws is the name of the window.

Python tkinter title bar text

Title bar is used to set the name or description of the window. In this section we will learn how to set the title of the window in python tkinter.

Syntax:

Here is the syntax for adding title to the window.

Code Snippet:

Here is the code to add title to the application window.

Output:

Here is the output of the above code. You can notice ‘PythonGuides’ as the title.

Python tkinter title bar text

Python tkinter title center

  • There is no official way of setting the title of application window to the center. But if you are a linux or mac os user then text will automatically appear in center of the title bar.
  • Windows user can apply some extra space to bring text to the center.

Python tkinter title color

  • Python tkinter title bar do not provide any option to set the color. Neither foreground color nor background color can be added.
  • Look and feel on Linux, Mac, and Windows may vary from each other.

Python Tkinter frame title

  • In this section, we will learn how to set title on the Tkinter frame. Also, we will share the common error messages & their fix.
  • Tkinter has provided two types of frame
    • Frame
    • LabelFrame

    python tkinter frame error

    The right way of adding title to the frame is by using Label Frame. Here is the demonstration.

    Code Snippet:

    Here is the code snippet to add title on the LabelFrame. You can notice in the output ‘PythonGuides’ is the title for the frame.

    Output:

    Here is the output of the above code snippet. You can notice there is PythonGuides written as the title of the frame.

    python tkinter LabelFrame

    Python tkinter remove title bar

    To remove title bar all you need to do is either delete the line ws.title(‘Any title’) or You can simply remove the text ‘Any title’. Here, any title is the title of the window.

    You may like the following Python Tkinter tutorials:

    In this tutorial, we have learned everything about Python Tkinter Title. Also, we have covered these topics.

    • python tkinter title
    • python tkinter title font size
    • python tkinter title bar color
    • python tkinter title bar text
    • python tkinter title center
    • python tkinter title color
    • python tkinter frame title
    • python tkinter remove title bar

    Bijay Kumar MVP

    Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

В этом уроке мы узнаем, как разрабатывать графические пользовательские интерфейсы, с помощью разбора некоторых примеров графического интерфейса Python с использованием библиотеки Tkinter.

Библиотека Tkinter установлена в Python в качестве стандартного модуля, поэтому нам не нужно устанавливать что-либо для его использования. Tkinter — очень мощная библиотека. Если вы уже установили Python, можете использовать IDLE, который является интегрированной IDE, поставляемой в Python, эта IDE написана с использованием Tkinter. Звучит круто!

Мы будем использовать Python 3.7 поэтому, если вы все еще используете Python 2.x, настоятельно рекомендуем перейти на Python 3.x, если вы не в курсе нюансов изменения языка, с целью, чтобы вы могли настроить код для запуска без ошибок.

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

Создание своего первого графического интерфейса

Для начала, следует импортировать Tkinter и создать окно, в котором мы зададим его название:

from tkinter import *


window = Tk()
window.title("Добро пожаловать в приложение PythonRu")
window.mainloop()

Результат будет выглядеть следующим образом:
Обучение Python GUI (уроки по Tkinter)Прекрасно! Наше приложение работает.
Последняя строка вызывает функцию mainloop. Эта функция вызывает бесконечный цикл окна, поэтому окно будет ждать любого взаимодействия с пользователем, пока не будет закрыто.

В случае, если вы забудете вызвать функцию mainloop , для пользователя ничего не отобразится.

Создание виджета Label

Чтобы добавить текст в наш предыдущий пример, мы создадим lbl , с помощью класса Label, например:

lbl = Label(window, text="Привет")

Затем мы установим позицию в окне с помощью функции grid и укажем ее следующим образом:

lbl.grid(column=0, row=0)

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

from tkinter import *  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
lbl = Label(window, text="Привет")  
lbl.grid(column=0, row=0)  
window.mainloop()

И вот как будет выглядеть результат:
Обучение Python GUI (уроки по Tkinter)Если функция grid не будет вызвана, текст не будет отображаться.

Настройка размера и шрифта текста

Вы можете задать шрифт текста и размер. Также можно изменить стиль шрифта. Для этого передайте параметр font таким образом:

lbl = Label(window, text="Привет", font=("Arial Bold", 50))

Обучение Python GUI (уроки по Tkinter)Обратите внимание, что параметр font может быть передан любому виджету, для того, чтобы поменять его шрифт, он применяется не только к Label.

Отлично, но стандартное окно слишком мало. Как насчет настройки размера окна?

Настройка размеров окна приложения

Мы можем установить размер окна по умолчанию, используя функцию geometry следующим образом:

window.geometry('400x250')

В приведенной выше строке устанавливается окно шириной до 400 пикселей и высотой до 250 пикселей.

Попробуем добавить больше виджетов GUI, например, кнопки и посмотреть, как обрабатывается нажатие кнопок.

Добавление виджета Button

Начнем с добавления кнопки в окно. Кнопка создается и добавляется в окно так же, как и метка:

btn = Button(window, text="Не нажимать!")
btn.grid(column=1, row=0)

Наш код будет выглядеть вот так:

from tkinter import *  
  

window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
lbl = Label(window, text="Привет", font=("Arial Bold", 50))  
lbl.grid(column=0, row=0)  
btn = Button(window, text="Не нажимать!")  
btn.grid(column=1, row=0)  
window.mainloop()

Результат будет следующим:
Обучение Python GUI (уроки по Tkinter)Обратите внимание, что мы помещаем кнопку во второй столбец окна, что равно 1. Если вы забудете и поместите кнопку в том же столбце, который равен 0, он покажет только кнопку.

Изменение цвета текста и фона у Button

Вы можете поменять цвет текста кнопки или любого другого виджета, используя свойство fg.
Кроме того, вы можете поменять цвет фона любого виджета, используя свойство bg.

btn = Button(window, text="Не нажимать!", bg="black", fg="red")

Обучение Python GUI (уроки по Tkinter)Теперь, если вы попытаетесь щелкнуть по кнопке, ничего не произойдет, потому что событие нажатия кнопки еще не написано.

Кнопка Click

Для начала, мы запишем функцию, которую нужно выполнить при нажатии кнопки:

def clicked():
    lbl.configure(text="Я же просил...")

Затем мы подключим ее с помощью кнопки, указав следующую ​​функцию:

btn = Button(window, text="Не нажимать!", command=clicked)

Обратите внимание: мы пишем clicked, а не clicked()с круглыми скобками. Теперь полный код будет выглядеть так:

from tkinter import *  
  
  
def clicked():  
    lbl.configure(text="Я же просил...")  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
lbl = Label(window, text="Привет", font=("Arial Bold", 50))  
lbl.grid(column=0, row=0)  
btn = Button(window, text="Не нажимать!", command=clicked)  
btn.grid(column=1, row=0)  
window.mainloop()

При нажатии на кнопку, результат, как и ожидалось, будет выглядеть следующим образом:
Обучение Python GUI (уроки по Tkinter)Круто!

Получение ввода с использованием класса Entry (текстовое поле Tkinter)

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

txt = Entry(window, width=10)

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

from tkinter import *  
  
  
def clicked():  
    lbl.configure(text="Я же просил...")  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
lbl = Label(window, text="Привет")  
lbl.grid(column=0, row=0)  
txt = Entry(window,width=10)  
txt.grid(column=1, row=0)  
btn = Button(window, text="Не нажимать!", command=clicked)  
btn.grid(column=2, row=0)  
window.mainloop()

Полученный результат будет выглядеть так:
Обучение Python GUI (уроки по Tkinter)Теперь, если вы нажмете кнопку, она покажет то же самое старое сообщение, но что же будет с отображением введенного текста в виджет Entry?

Во-первых, вы можете получить текст ввода, используя функцию get. Мы можем записать код для выбранной функции таким образом:

def clicked():
    res = "Привет {}".format(txt.get())
    lbl.configure(text=res)

Если вы нажмете на кнопку — появится текст «Привет » вместе с введенным текстом в виджете записи. Вот полный код:

from tkinter import *  
  
  
def clicked():  
    res = "Привет {}".format(txt.get())  
    lbl.configure(text=res)  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
lbl = Label(window, text="Привет")  
lbl.grid(column=0, row=0)  
txt = Entry(window,width=10)  
txt.grid(column=1, row=0)  
btn = Button(window, text="Клик!", command=clicked)  
btn.grid(column=2, row=0)  
window.mainloop()

Запустите вышеуказанный код и проверьте результат:
Обучение Python GUI (уроки по Tkinter)Прекрасно!

Каждый раз, когда мы запускаем код, нам нужно нажать на виджет ввода, чтобы настроить фокус на ввод текста, но как насчет автоматической настройки фокуса?

Установка фокуса виджета ввода

Здесь все очень просто, ведь все, что нам нужно сделать, — это вызвать функцию focus:

txt.focus()

Когда вы запустите свой код, вы заметите, что виджет ввода в фокусе, который дает возможность сразу написать текст.

Отключить виджет ввода

Чтобы отключить виджет ввода, отключите свойство состояния:

txt = Entry(window,width=10, state='disabled')

Обучение Python GUI (уроки по Tkinter)Теперь вы не сможете ввести какой-либо текст.

Добавление виджета Combobox

Чтобы добавить виджет поля с выпадающем списком, используйте класс Combobox из ttk следующим образом:

from tkinter.ttk import Combobox


combo = Combobox(window)

Затем добавьте свои значения в поле со списком.

from tkinter import *  
from tkinter.ttk import Combobox  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
combo = Combobox(window)  
combo['values'] = (1, 2, 3, 4, 5, "Текст")  
combo.current(1)  # установите вариант по умолчанию  
combo.grid(column=0, row=0)  
window.mainloop()

Обучение Python GUI (уроки по Tkinter)Как видите с примера, мы добавляем элементы combobox, используя значения tuple.
Чтобы установить выбранный элемент, вы можете передать индекс нужного элемента текущей функции.
Чтобы получить элемент select, вы можете использовать функцию get вот таким образом:

combo.get()

Добавление виджета Checkbutton (чекбокса)

С целью создания виджета checkbutton, используйте класс Checkbutton:

from tkinter.ttk import Checkbutton


chk = Checkbutton(window, text='Выбрать')

Кроме того, вы можете задать значение по умолчанию, передав его в параметр var в Checkbutton:

from tkinter import *  
from tkinter.ttk import Checkbutton  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
chk_state = BooleanVar()  
chk_state.set(True)  # задайте проверку состояния чекбокса  
chk = Checkbutton(window, text='Выбрать', var=chk_state)  
chk.grid(column=0, row=0)  
window.mainloop()

Посмотрите на результат:
Обучение Python GUI (уроки по Tkinter)

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

Здесь мы создаем переменную типа BooleanVar, которая не является стандартной переменной Python, это переменная Tkinter, затем передаем ее классу Checkbutton, чтобы установить состояние чекбокса как True в приведенном выше примере.

Вы можете установить для BooleanVar значение false, что бы чекбокс не был отмечен.
Так же, используйте IntVar вместо BooleanVar и установите значения 0 и 1.

chk_state = IntVar()
chk_state.set(0) # False
chk_state.set(1) # True

Эти примеры дают тот же результат, что и BooleanVar.

Добавление виджетов Radio Button

Чтобы добавить radio кнопки, используйте класс RadioButton:

rad1 = Radiobutton(window,text='Первый', value=1)

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

from tkinter import *  
from tkinter.ttk import Radiobutton  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
rad1 = Radiobutton(window, text='Первый', value=1)  
rad2 = Radiobutton(window, text='Второй', value=2)  
rad3 = Radiobutton(window, text='Третий', value=3)  
rad1.grid(column=0, row=0)  
rad2.grid(column=1, row=0)  
rad3.grid(column=2, row=0)  
window.mainloop()

Результатом вышеприведенного кода будет следующий:
Обучение Python GUI (уроки по Tkinter)Кроме того, вы можете задать command любой из этих кнопок для определенной функции. Если пользователь нажимает на такую кнопку, она запустит код функции.
Вот пример:

rad1 = Radiobutton(window,text='Первая', value=1, command=clicked)

def clicked():
    # Делайте, что нужно

Достаточно легко!

Получение значения Radio Button (Избранная Radio Button)

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

from tkinter import *  
from tkinter.ttk import Radiobutton  
  
  
def clicked():  
    lbl.configure(text=selected.get())  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
selected = IntVar()  
rad1 = Radiobutton(window,text='Первый', value=1, variable=selected)  
rad2 = Radiobutton(window,text='Второй', value=2, variable=selected)  
rad3 = Radiobutton(window,text='Третий', value=3, variable=selected)  
btn = Button(window, text="Клик", command=clicked)  
lbl = Label(window)  
rad1.grid(column=0, row=0)  
rad2.grid(column=1, row=0)  
rad3.grid(column=2, row=0)  
btn.grid(column=3, row=0)  
lbl.grid(column=0, row=1)  
window.mainloop()

Обучение Python GUI (уроки по Tkinter)Каждый раз, когда вы выбираете radio button, значение переменной будет изменено на значение кнопки.

Добавление виджета ScrolledText (текстовая область Tkinter)

Чтобы добавить виджет ScrolledText, используйте класс ScrolledText:

from tkinter import scrolledtext


txt = scrolledtext.ScrolledText(window,width=40,height=10)

Здесь нужно указать ширину и высоту ScrolledText, иначе он заполнит все окно.

from tkinter import *  
from tkinter import scrolledtext  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
txt = scrolledtext.ScrolledText(window, width=40, height=10)  
txt.grid(column=0, row=0)  
window.mainloop()

Результат:
Обучение Python GUI (уроки по Tkinter)

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

Используйте метод insert, чтобы настроить содержимое Scrolledtext:

txt.insert(INSERT, 'Текстовое поле')

Удаление/Очистка содержимого Scrolledtext

Чтобы очистить содержимое данного виджета, используйте метод delete:

txt.delete(1.0, END)  # мы передали координаты очистки

Отлично!

Создание всплывающего окна с сообщением

Чтобы показать всплывающее окно с помощью Tkinter, используйте messagebox следующим образом:

from tkinter import messagebox


messagebox.showinfo('Заголовок', 'Текст')

Довольно легко! Давайте покажем окно сообщений при нажатии на кнопку пользователем.

from tkinter import *  
from tkinter import messagebox  
  
  
def clicked():  
    messagebox.showinfo('Заголовок', 'Текст')  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
btn = Button(window, text='Клик', command=clicked)  
btn.grid(column=0, row=0)  
window.mainloop()

Обучение Python GUI (уроки по Tkinter)Когда вы нажмете на кнопку, появится информационное окно.

Показ сообщений о предупреждениях и ошибках

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

messagebox.showwarning('Заголовок', 'Текст')  # показывает предупреждающее сообщение
messagebox.showerror('Заголовок', 'Текст')  # показывает сообщение об ошибке

Показ диалоговых окон с выбором варианта

Чтобы показать пользователю сообщение “да/нет”, вы можете использовать одну из следующих функций messagebox:

from tkinter import messagebox


res = messagebox.askquestion('Заголовок', 'Текст')
res = messagebox.askyesno('Заголовок', 'Текст')
res = messagebox.askyesnocancel('Заголовок', 'Текст')
res = messagebox.askokcancel('Заголовок', 'Текст')
res = messagebox.askretrycancel('Заголовок', 'Текст')

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

Если вы кликнете OK, yes или retry, значение станет True, а если выберете no или cancel, значение будет False.
Единственной функцией, которая возвращает одно из трех значений, является функция askyesnocancel; она возвращает True/False/None.

Добавление SpinBox (Виджет спинбокс)

Для создания виджета спинбокса, используйте класс Spinbox:

spin = Spinbox(window, from_=0, to=100)

Таким образом, мы создаем виджет Spinbox, и передаем параметры from и to, чтобы указать диапазон номеров.
Кроме того, вы можете указать ширину виджета с помощью параметра width:

spin = Spinbox(window, from_=0, to=100, width=5)

Проверим пример полностью:

from tkinter import *  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
spin = Spinbox(window, from_=0, to=100, width=5)  
spin.grid(column=0, row=0)  
window.mainloop()

Обучение Python GUI (уроки по Tkinter)Вы можете указать числа для Spinbox, вместо использования всего диапазона следующим образом:

spin = Spinbox(window, values=(3, 8, 11), width=5)

Виджет покажет только эти 3 числа: 3, 8 и 11.

Задать значение по умолчанию для Spinbox

В случае, если вам нужно задать значение по умолчанию для Spinbox, вы можете передать значение параметру textvariable следующим образом:

var = IntVar()
var.set(36)
spin = Spinbox(window, from_=0, to=100, width=5, textvariable=var)

Теперь, если вы запустите программу, она покажет 36 как значение по умолчанию для Spinbox.

Добавление виджета Progressbar

Чтобы создать данный виджет, используйте класс progressbar :

from tkinter.ttk import Progressbar


bar = Progressbar(window, length=200)

Установите значение progressbar таким образом:

bar['value'] = 70

Вы можете установить это значение на основе любого процесса или при выполнении задачи.

Изменение цвета Progressbar

Изменение цвета Progressbar немного сложно. Сначала нужно создать стиль и задать цвет фона, а затем настроить созданный стиль на Progressbar. Посмотрите следующий пример:

from tkinter import *  
from tkinter.ttk import Progressbar  
from tkinter import ttk  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
style = ttk.Style()  
style.theme_use('default')  
style.configure("black.Horizontal.TProgressbar", background='black')  
bar = Progressbar(window, length=200, style='black.Horizontal.TProgressbar')  
bar['value'] = 70  
bar.grid(column=0, row=0)  
window.mainloop()

И в результате вы получите следующее:
Обучение Python GUI (уроки по Tkinter)

Добавление поля загрузки файла

Для добавления поля с файлом, используйте класс filedialog:

from tkinter import filedialog


file = filedialog.askopenfilename()

После того, как вы выберете файл, нажмите “Открыть”; переменная файла будет содержать этот путь к файлу. Кроме того, вы можете запросить несколько файлов:

files = filedialog.askopenfilenames()

Указание типа файлов (расширение фильтра файлов)

Возможность указания типа файлов доступна при использовании параметра filetypes, однако при этом важно указать расширение в tuples.

file = filedialog.askopenfilename(filetypes = (("Text files","*.txt"),("all files","*.*")))

Вы можете запросить каталог, используя метод askdirectory :

dir = filedialog.askdirectory()

Вы можете указать начальную директорию для диалогового окна файла, указав initialdir следующим образом:

from os import path
file = filedialog.askopenfilename(initialdir= path.dirname(__file__))

Легко!

Добавление панели меню

Для добавления панели меню, используйте класс menu:

from tkinter import Menu


menu = Menu(window)
menu.add_command(label='Файл')
window.config(menu=menu)

Сначала мы создаем меню, затем добавляем наш первый пункт подменю. Вы можете добавлять пункты меню в любое меню с помощью функции add_cascade() таким образом:

menu.add_cascade(label='Автор', menu=new_item)

Наш код будет выглядеть так:

from tkinter import *  
from tkinter import Menu  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
menu = Menu(window)  
new_item = Menu(menu)  
new_item.add_command(label='Новый')  
menu.add_cascade(label='Файл', menu=new_item)  
window.config(menu=menu)  
window.mainloop()

Обучение Python GUI (уроки по Tkinter)Таким образом, вы можете добавить столько пунктов меню, сколько захотите.

from tkinter import *  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
menu = Menu(window)  
new_item = Menu(menu)  
new_item.add_command(label='Новый')  
new_item.add_separator()  
new_item.add_command(label='Изменить')  
menu.add_cascade(label='Файл', menu=new_item)  
window.config(menu=menu)  
window.mainloop()

Обучение Python GUI (уроки по Tkinter)Теперь мы добавляем еще один пункт меню “Изменить” с разделителем меню. Вы можете заметить пунктирную линию в начале, если вы нажмете на эту строку, она отобразит пункты меню в небольшом отдельном окне.

Можно отключить эту функцию, с помощью tearoff подобным образом:

new_item = Menu(menu, tearoff=0)

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

new_item.add_command(label='Новый', command=clicked)

Добавление виджета Notebook (Управление вкладкой)

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

  • Для начала, создается элемент управления вкладкой, с помощью класса Notebook .
  • Создайте вкладку, используя класс Frame.
  • Добавьте эту вкладку в элемент управления вкладками.
  • Запакуйте элемент управления вкладкой, чтобы он стал видимым в окне.
from tkinter import *  
from tkinter import ttk  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
tab_control = ttk.Notebook(window)  
tab1 = ttk.Frame(tab_control)  
tab_control.add(tab1, text='Первая')  
tab_control.pack(expand=1, fill='both')  
window.mainloop()

Обучение Python GUI (уроки по Tkinter)Таким образом, вы можете добавлять столько вкладок, сколько нужно.

Добавление виджетов на вкладку

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

from tkinter import *  
from tkinter import ttk  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение PythonRu")  
window.geometry('400x250')  
tab_control = ttk.Notebook(window)  
tab1 = ttk.Frame(tab_control)  
tab2 = ttk.Frame(tab_control)  
tab_control.add(tab1, text='Первая')  
tab_control.add(tab2, text='Вторая')  
lbl1 = Label(tab1, text='Вкладка 1')  
lbl1.grid(column=0, row=0)  
lbl2 = Label(tab2, text='Вкладка 2')  
lbl2.grid(column=0, row=0)  
tab_control.pack(expand=1, fill='both')  
window.mainloop()

Обучение Python GUI (уроки по Tkinter)

Добавление интервала для виджетов (Заполнение)

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

Передайте padx и pady любому виджету и задайте значение.

lbl1 = Label(tab1, text= 'label1', padx=5, pady=5)

Это очень просто!

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

Понравилась статья? Поделить с друзьями:
  • Как изменить название окна python
  • Как изменить название окей гугл
  • Как изменить название объявления на авито
  • Как изменить название объекта на яндекс картах
  • Как изменить название объекта на гугл картах