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

I'm running several instances of a certain Python script on a Windows machine, each from a different directory and using a separate shell windows. Unfortunately Windows gives each of these shell wi...

I’m running several instances of a certain Python script on a Windows machine, each from a different directory and using a separate shell windows. Unfortunately Windows gives each of these shell windows the same name:

<User>: C:Windowssystem32cmd.exe - <script.py>

Is it possible to set this name to something else through a Python command?

user3666197's user avatar

asked Sep 12, 2011 at 11:40

Jonathan Livni's user avatar

Jonathan LivniJonathan Livni

98.5k103 gold badges260 silver badges355 bronze badges

1

On Windows, a simple console command will suffice:

from os import system
system("title " + myCoolTitle)

Nice and easy.

Nick stands with Ukraine's user avatar

answered Apr 19, 2012 at 13:50

ShouravBR's user avatar

4

This works for Python2.7 under Windows.

>>> import ctypes
>>> ctypes.windll.kernel32.SetConsoleTitleA("My New Title")

answered Sep 27, 2012 at 16:56

Jeffrey Harper's user avatar

4

Due to not enough rep I cannot add a comment to the above post — so as a new post.

In Python 3 you can use:

import ctypes
ctypes.windll.kernel32.SetConsoleTitleW("My New Title")

I edited this answer: please remark, that it now uses SetConsoleTitleW, which is the Unicode version of the SetConsoleTitle function.
This way you can use unicode and no longer have to encode the string/variable to a byte object. You can just replace the argument with the string variable.

answered Jan 1, 2014 at 1:33

user136036's user avatar

user136036user136036

10.5k6 gold badges45 silver badges46 bronze badges

2

Since you’re only going to be running this on Windows (IOW, there’s not a cross-platform way to do this):

  1. Download & install the Win32 extensions for python
  2. Inside of your script, you can change the title of the console with the function

    win32console.SetConsoleTitle("My Awesome App")

answered Sep 12, 2011 at 13:04

bgporter's user avatar

bgporterbgporter

34.4k8 gold badges60 silver badges65 bronze badges

Comparison of the posted system() & windll-based methods

tying to add a small quantitative comparison of latency overheads associated with two of the posted methods:

|>>> from zmq import Stopwatch
|>>> aSWX = Stopwatch()

|>>> from os import system
|>>> aSWX.start();system( 'TITLE os_SHELL_CMD_TITLE_TXT');aSWX.stop()  15149L [us]
|>>> aSWX.start();system( 'TITLE os_SHELL_CMD_TITLE_TXT');aSWX.stop()  15347L [us]
|>>> aSWX.start();system( 'TITLE os_SHELL_CMD_TITLE_TXT');aSWX.stop()  15000L [us]
|>>> aSWX.start();system( 'TITLE os_SHELL_CMD_TITLE_TXT');aSWX.stop()  14674L [us]
|>>> aSWX.start();system( 'TITLE os_SHELL_CMD_TITLE_TXT');aSWX.stop()  14774L [us]
|>>> aSWX.start();system( 'TITLE os_SHELL_CMD_TITLE_TXT');aSWX.stop()  14551L [us]
|>>> aSWX.start();system( 'TITLE os_SHELL_CMD_TITLE_TXT');aSWX.stop()  14633L [us]
|>>> aSWX.start();system( 'TITLE os_SHELL_CMD_TITLE_TXT');aSWX.stop()  15202L [us]
|>>> aSWX.start();system( 'TITLE os_SHELL_CMD_TITLE_TXT');aSWX.stop()  14889L [us]

|>>> from ctypes import windll
|>>> aSWX.start();windll.kernel32.SetConsoleTitleA('DLL');aSWX.stop()   5767L [us]
|>>> aSWX.start();windll.kernel32.SetConsoleTitleA('DLL');aSWX.stop()    643L [us]
|>>> aSWX.start();windll.kernel32.SetConsoleTitleA('DLL');aSWX.stop()    573L [us]
|>>> aSWX.start();windll.kernel32.SetConsoleTitleA('DLL');aSWX.stop()    749L [us]
|>>> aSWX.start();windll.kernel32.SetConsoleTitleA('DLL');aSWX.stop()    689L [us]
|>>> aSWX.start();windll.kernel32.SetConsoleTitleA('DLL');aSWX.stop()    651L [us]

In cases, where one might spend about a half of millisecond ( but not some tens of that ) the windll.kernel32 method seems promising and may serve better for an alternative display of a WatchDOG / StateVARs / ProgressLOG / auto-self-diagnostic messages, being efficiently displayed in a soft real-time need, during long running processes.

answered Oct 11, 2015 at 1:13

user3666197's user avatar

I am not aware of a way to change the cmd window title from within the script.

However, you can set the title when launching the script if you use the start command.

answered Sep 12, 2011 at 11:53

NPE's user avatar

NPENPE

479k105 gold badges940 silver badges1006 bronze badges

1

If starting the Idle-shell is an option instead of the cmd shell:

idle.py [-c command] [-d] [-e] [-s] [-t title] [arg] ...

-c command  run this command
-d          enable debugger
-e          edit mode; arguments are files to be edited
-s          run $IDLESTARTUP or $PYTHONSTARTUP first
-t title    set title of shell window

answered Sep 12, 2011 at 11:54

Remi's user avatar

RemiRemi

20.2k8 gold badges55 silver badges41 bronze badges

Use:

import ctypes
ctypes.windll.kernel32.SetConsoleTitleW('new title')

Or:

import os
os.system('title new title')

answered Dec 6, 2021 at 6:37

Pixelsuft's user avatar

1

It is now possible to change the window title from within any language via outputting a standard escape sequence to the console (stdout). Here’s a working example from a batch file Change command prompt to only show current directory name however just printing ESC close-bracket 2 semicolon your-title-here BEL (control-G) will do it. Also an easily adapted PHP example:

function windowTitle($title)
  {printf("33]2;%s07", $title);}

answered Oct 9, 2018 at 22:30

mike_n's user avatar

2

Using OS module To interact with the terminal

  1. Import the library — import os
  2. Interact with the terminal to change title — os.system('title your_tile')

Explanation:

So if you open your terminal and type title your_title is will change the terminal title to your_title
CMD

In Python the OS.system() is used to type into the terminal

This is how you will change title of terminal with Python

answered Jun 21, 2022 at 17:45

unofficialdxnny's user avatar

python

  • Python

  • Командная строка

Как изменить название консольного окна Python? Или какой модуль для этого используется?


  • Вопрос задан

    более двух лет назад

  • 1211 просмотров



3

комментария

  • Если я не ошибаюсь при помощи встроенного модуля: ctypes

    Что-то наподобие:

    import ctypes
    
    ctypes.windll.kernel32.SetConsoleTitleA("Console name")

  • Богдан

    @Bogdikon Автор вопроса

    MaBa2014, Только одна буква из названия появляется

  • Богдан, import ctypes

    ctypes.windll.kernel32.SetConsoleTitleA(b»Console name»)


Решения вопроса 1

import ctypes

ctypes.windll.kernel32.SetConsoleTitleA(b»you have to use bytes instead str here»)


Комментировать

Пригласить эксперта


Похожие вопросы


  • Показать ещё
    Загружается…

10 февр. 2023, в 17:14

20000 руб./за проект

10 февр. 2023, в 17:11

20000 руб./за проект

10 февр. 2023, в 16:57

1500 руб./за проект

Минуточку внимания

Окна

В этом уроке рассмотрим основные настройки окон, в которых располагаются виджеты. Обычные окна в 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-приложение.

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

Последнее обновление: 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)

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.

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.

programmy-na-pyqt5.png

В этой части руководства PyQt5

мы изучим некоторую базовую функциональность.

Этот простой пример выводит маленькое окно. Мы можем делать множество вещей с этим окном. Мы можем менять его размер, раскрывать на весь экран или свернуть в панель задач. Это потребовало бы много программного кода. Кто-то уже запрограммировал эту функциональность. Поскольку это повторяется в большинстве приложений, нет необходимости программировать это с самого начала. PyQt5 – это инструментарий высокого уровня. Если бы мы писали с помощью инструментов более низкого уровня, нижеследующий пример кода мог бы с лёгкостью содержать сотни строк.

#!/usr/bin/python3
# -*- coding: utf-8 -*-
 
import sys
from PyQt5.QtWidgets import QApplication, QWidget
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QWidget()
    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('Simple')
    w.show()
    
    sys.exit(app.exec_())

Пример кода выше выводит маленькое окно на экране.

import sys
from PyQt5.QtWidgets import QApplication, QWidget

Здесь мы обеспечили необходимый импорт модулей. Основные виджеты расположены в модуле PyQt5.QtWidgets.

app = QApplication(sys.argv)

Каждое приложение PyQt5 должно создать объект приложения. Параметр sys.argv — это список аргументов из командной строки. Скрипты Python могут быть запущены из программной оболочки. Это один из способов, как мы можем контролировать запуск наших скриптов.

w = QWidget()

Виджет QWidget – это основной класс всех объектов пользовательского интерфейса в PyQt5. Мы обеспечиваем конструктор по умолчанию для QWidget. Конструктор по умолчанию не имеет родителя. Виджет без родителя называется окном.

w.resize(250, 150)

Метод resize() изменяет размер виджета. Здесь задана ширина 250px и высота 150px.

w.move(300, 300)

Метод move() перемещает виджет на позицию с координатами x=300 и y=300 на экране.

w.setWindowTitle('Simple')

Здесь мы устанавливаем название нашего окна. Оно показывается в строке заголовка.

w.show()

Метод show() отображает виджет на экране. Виджет сначала создаётся в памяти и позже показывается на экране.

sys.exit(app.exec_())

Наконец, мы входим в главный цикл приложения. Обработка событий начинается в этой точке. Главный цикл получает события из системы и отправляет их виджетам приложения. Цикл завершается, если мы вызываем метод exit() или главное окно было закрыто. Метод sys.exit() гарантирует чистый выход. Среда будет проинформирована, когда приложение завершится.

Метод exec_() содержит нижнее подчеркивание, потому что exec – уже используемое имя в Python. И, соответственно, имя exec_() было использовано взамен.

Окно Simple

Рисунок: Окно Simple

Иконка приложения

Иконка приложения – это маленькое изображение, которое обычно отображается в верхнем левом углу строки заголовка. В следующем примере мы увидим, как сделать её в PyQt5. Мы также познакомимся с несколькими новыми методами.

#!/usr/bin/python3
# -*- coding: utf-8 -*-
 
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
 
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        self.setGeometry(300, 300, 300, 220)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QIcon('web.png'))        
    
        self.show()
        
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())  

Предыдущий пример был написан в процедурном стиле. Язык программирования Python поддерживает и процедурный, и объектно-ориентированный стиль программирования. Программирование в PyQt5 означает объектно-ориентированное программирование (ООП).

class Example(QWidget):
    def __init__(self):
        super().__init__()
        ...

Есть три важных вещи в объектно-ориентированном программировании – это классы, данные и методы. Здесь мы создаём новый класс с именем Example. Класс Example наследуется из класса QWidget. Это значит, что мы вызываем два конструктора: первый для класса Example и второй для унаследованного класса. Метод super() возвращает объект родителя класса Example и мы вызываем его конструктор. Метод __init__() – это конструктор класса в языке Python.

self.initUI()

Создание GUI поручено методу initUI().

self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.png'))

Все три метода были унаследованы из класса QWidget. setGeometry делает две вещи: он определяет место окна на экране и устанавливает его размер. Первые два параметра – позиции x и y нашего окна. Третий – ширина, и четвёртый – высота окна. Фактически, setGeometry сочетает методы resize() и move() в одном. Последний метод устанавливает иконку приложения. Чтобы сделать это, мы создали объект QIcon. QIcon принимает путь к нашей иконке для её отображения.

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

Приложение и объекты примера созданы. Главный цикл запущен.

Окно с иконкой

Рисунок: Окно с иконкой

Показ всплывающих подсказок

Мы можем обеспечить любой из наших виджетов всплывающей подсказкой.

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import (QWidget, QToolTip, QPushButton, QApplication)
from PyQt5.QtGui import QFont    
class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        self.initUI()
        
        
    def initUI(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        
        self.setToolTip('This is a <b>QWidget</b> widget')
        
        btn = QPushButton('Button', self)
        btn.setToolTip('This is a <b>QPushButton</b> widget')
        btn.resize(btn.sizeHint())
        btn.move(50, 50)       
        
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Tooltips')    
        self.show()
        
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

В этом примере, мы показываем подсказку для двух PyQt5 виджетов.

QToolTip.setFont(QFont('SansSerif', 10))

Этот статический метод устанавливает шрифт, используемый для показа всплывающих подсказок. Мы используем шрифт 10px SansSerif.

self.setToolTip('This is a <b>QWidget</b> widget')

Чтобы создать подсказку, мы вызываем метод setTooltip(). Мы можем использовать HTML форматирование текста.

btn = QPushButton('Button', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')

Мы создаём виджет кнопки и устанавливаем всплывающую подсказку для неё.

btn.resize(btn.sizeHint())
btn.move(50, 50)

Меняем размер у кнопки, перемещаем её в окно. Метод sizeHint() даёт рекомендуемый размер для кнопки.

Всплывающие подсказки

Рисунок: Всплывающие подсказки

Закрытие окна

Очевидный способ закрыть окно – это кликнуть на знаке «X» в строке заголовка. В следующем примере, мы покажем, как мы можем программно закрыть наше окно. Мы кратко коснёмся темы сигналов и слотов.

Ниже следует конструктор виджета QPushButton, который мы используем в нашем примере.

QPushButton(string_text, QWidget parent = None)

Параметр string_text – это текст, который будет отображён на кнопке. Parent – это виджет, на котором мы разместим нашу кнопку. В этом случае это будет QWidget.

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

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtCore import QCoreApplication
 
class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):               
        qbtn = QPushButton('Quit', self)
        qbtn.clicked.connect(QCoreApplication.instance().quit)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(50, 50)       
        
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Quit button')    
        self.show()
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

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

from PyQt5.QtCore import QCoreApplication

Нам необходим объект из модуля QtCore.

qbtn = QPushButton('Quit', self)

Мы создали кнопку. Кнопка является образцом класса QPushButton. Первый параметр конструктора – это метка кнопки. Второй параметр – родительский виджет. Виджет родителя – это Example, который наследуется из QWidget.

qbtn.clicked.connect(QCoreApplication.instance().quit)

Система обработки событий в PyQt5 построена на механизме сигналов и слотов. Если мы кликаем по кнопке, выдаётся сигнал clicked. Слот может быть слотом Qt или любым слотом, вызываемым из Python. QCoreApplication содержит цикл главного события; он обрабатывает и выполняет все события. Метод instance даёт нам его текущий экземпляр. Заметим, что QCoreApplication создаётся с QApplication. Кликнутый сигнал соединяется с методом quit(), который и завершает приложение. Взаимосвязь сделана между двумя объектами: отправителем и получателем. Отправитель – нажатие кнопки, получатель – объект приложения.

Кнопка выхода

Рисунок: Кнопка выхода

Диалоговое окно

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

#!/usr/bin/python3
# -*- coding: utf-8 -*-
 
import sys
from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication
 
class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):               
        self.setGeometry(300, 300, 250, 150)        
        self.setWindowTitle('Message box')    
        self.show()
        
    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()        
        
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

Если мы закрываем QWidget, вызывается QCloseEvent. Чтобы изменить поведение виджета, нам необходимо переопределить обработчик событий closeEvent().

reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

Мы показываем сообщение с двумя кнопками: «Yes» и «No». Первая строка появляется в строке заголовка. Вторая строка – это текст сообщения, отображаемый с помощью диалогового окна. Третий аргумент указывает комбинацию кнопок, появляющихся в диалоге. Последний параметр – кнопка по умолчанию. Это кнопка, которая первоначально имеет на себе указатель клавиатуры. Возвращаемое значение хранится в переменной reply.

if reply == QtGui.QMessageBox.Yes:
    event.accept()
else:
    event.ignore()

Здесь мы проверяем возвращаемое значение. Если мы кликаем кнопку «Yes», мы принимаем событие, которое ведёт к закрытию виджета и завершению приложения. В противном случае, мы игнорируем закрывающее событие.

Диалоговое окно

Рисунок: Диалоговое окно

Центрирование окна на экране

Нижеследующий скрипт показывает, как мы можем центрировать окно экране.

#!/usr/bin/python3
# -*- coding: utf-8 -*-
 
import sys
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication
 
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):               
        self.resize(250, 150)
        self.center()
        self.setWindowTitle('Center')    
        self.show()
        
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

Класс QtGui.QDesktopWidget предоставляет информацию о пользовательском рабочем столе, включая размер экрана.

self.center()

Код, который будет центрировать окно, размещён в специальном методе center().

qr = self.frameGeometry()

Мы получаем прямоугольник, точно определяющий форму главного окна.

cp = QDesktopWidget().availableGeometry().center()

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

qr.moveCenter(cp)

Наш прямоугольник уже имеет высоту и ширину. Теперь мы устанавливаем центр прямоугольника в центр экрана. Размер прямоугольника не изменяется.

self.move(qr.topLeft())

Мы перемещаем верхнюю левую точку окна приложения в верхнюю левую точку прямоугольника qr, таким образом центрируя окно на нашем экране.

В этой части руководства PyQt5, мы успели изучить некоторые основы…

Продолжение: Меню и панели инструментов в PyQt5 [Урок №3]

Прошлый урок: Введение в PyQt5 [Урок 1]

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