Python tkinter окно вывода

# Создание диалогового окна

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

Создадим свое диалоговое окно. Для примера оно создается используя несколько виджетов:

from tkinter import * window = Tk() window.title("Message box title") window.geometry("300x75") label = Label(window, text="My message content!") label.pack() button = Button(window, text="Ok", width=10, command=window.destroy) button.pack(side=RIGHT) window.mainloop() 

Мы получили простейшее диалоговое окно, и хотя диалоговые окна весьма разнообразны, их вид уже устоялся. Нет необходимости создавать диалоговые окна с нуля, для это можно использовать «заготовки».

# Messagebox — окно с информацией

Для информирования пользователя о процессах происходящих в ПК можно использовать messagebox — окно с информацией. При этом требуется дополнительно импортировать «подмодуль» tkinter — tkinter.messagbox , в котором описаны классы для окон данного типа.

Код созданного информационного окна может быть следующим:

from tkinter import messagebox messagebox.showinfo('Message title', 'Message info content') 

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

from tkinter import messagebox messagebox.showwarning('Message warning title', 'Message warning content') # show warning message 

messagebox_warning

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

from tkinter import messagebox messagebox.showerror('Message error title', 'Message error content') # show error message 

messagebox_error

# Messagebox — окно с вопросом

Следующие примеры диалоговых окон, служат для ведения диалога программы с пользователем и сохранением его ответа в переменной.

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

from tkinter import messagebox response = messagebox.askquestion('Message title', 'Message ask content') response = messagebox.askyesno('Message title', 'Message y/n content') response = messagebox.askyesnocancel('Message title', 'Message y/n/cancel content') response = messagebox.askokcancel('Message title', 'Message ok/cancel content') response = messagebox.askretrycancel('Message title', 'Message retry/cancel content') 

# Упражнения

  1. Исследование: после каждого вызова диалогового окна добавьте команду print(response) , которая выведет в консоль значение выбранного варианта ответа.

# Окна открытия и сохранения файлов

Рассмотрим, как запрограммировать с помощью tkinter вызов диалоговых окон открытия и сохранения файлов и работу с ними. При этом требуется дополнительно импортировать «подмодуль» tkinter — tkinter.filedialog , в котором описаны классы для окон данного типа:

from tkinter import * from tkinter import filedialog root = Tk() document_open = filedialog.askopenfilename() document_save = filedialog.asksaveasfilename() root.mainloop() 

Здесь создаются два объекта ( document_open и document_save ): один вызывает диалоговое окно «Открыть», а другой «Сохранить как…». При выполнении скрипта, они друг за другом выводятся на экран после появления главного окна. Если не создать root, то оно все-равно появится на экране, однако при попытке его закрытия в конце возникнет ошибка.

# Упражнения

  1. Исследование: выведите в консоль результат вашего выбора в диалоговом окне.
  2. Что будет результатом вывода в консоль при выборе папок/файлов в диалоговых окнах и нажатии кнопки «ок»?
  3. Напишите программу с вызовом всех типов диалоговых окон для работы с файлами. Сколько их? И какие различия? (подскажет их PyCharm, когда наберете filedialog.ask )

Источник

Пример ввода и вывода данных в программе с GUI на базе Tkinter

Текст, введённый в первую строку главного окна программы, при нажатии на кнопку «Вывод» отображается во второй строке, а при нажатии на кнопку «Сообщение» — в окне сообщения.

 # Импортируем библиотеку Tkinter. import tkinter # Импортируем модуль сообщений из библиотеки Tkinter. import tkinter.messagebox # Создаём класс главного окна программы. class MyGui: # Создаём конструктор класса главного окна программы. def __init__(self): # Создаём главное окно. self.main_window = tkinter.Tk() # Устанавливаем заголовок для главного окна программы. self.main_window.title("Главное окно") # Устаналиваем размеры для главного окна программы в пикселях . self.main_window.geometry('230x160') # Создаём надпись "Ввод". self.label = tkinter.Label(self.main_window, text="Ввод") # Располагаем надпись "Ввод" в главном окне программы. self.label.pack() # Создаём строку для ввода текста. self.entry_vvod = tkinter.Entry(self.main_window) # Располагаем строку для ввода текста в главном окне программы. self.entry_vvod.pack() # Создаём кнопку "Вывод". # В качестве команды указываем функцию "vyvod". self.button_vyvod = tkinter.Button(self.main_window, text="Вывод", command=self.vyvod) # Располагаем кнопку "Вывод" в главном окне программы. self.button_vyvod.pack() # Создаём переменную "text" при помощи метода "StringVar()". self.text = tkinter.StringVar() # Создаём строку для вывода текста. # Содержание этой строки зависит от переменной "text". self.entry_vyvod = tkinter.Entry(self.main_window, textvariable=self.text) # Располагаем строку для вывода текста в главном окне программы. self.entry_vyvod.pack() # Создаём кнопку "Сообщение". # В качестве команды указываем функцию "soobshenie". self.button_soobshenie = tkinter.Button(self.main_window, text="Сообщение", command=self.soobshenie) # Располагаем кнопку "Сообщение" в главном окне программы. self.button_soobshenie.pack() # Создаём кнопку "Выход". # В качестве команды указываем метод 'destroy' для главного окна программы. self.button_exit = tkinter.Button(self.main_window, text="Выход", command=self.main_window.destroy) # Располагаем кнопку "Выход" в главном окне программы. self.button_exit.pack() # Выводим главное окно на экран. tkinter.mainloop() # Создаём функцию для вывода текста в строку. def vyvod(self): # Берём текст из строки ввода и кладём его в переменную "text". self.text.set(self.entry_vvod.get()) # Создаём функцию для вывода текста в сообщении. def soobshenie(self): # Берём текст из строки ввода и выводим его в окне сообщения. tkinter.messagebox.showinfo('Сообщение',self.entry_vvod.get()) # Создаём экземпляр главного окна программы new_window = MyGui() 

Добавить комментарий

Для отправки комментария вам необходимо авторизоваться.

Источник

Tkinter Dialogs¶

tkinter.simpledialog — Standard Tkinter input dialogs¶

The tkinter.simpledialog module contains convenience classes and functions for creating simple modal dialogs to get a value from the user.

tkinter.simpledialog. askfloat ( title , prompt , ** kw ) ¶ tkinter.simpledialog. askinteger ( title , prompt , ** kw ) ¶ tkinter.simpledialog. askstring ( title , prompt , ** kw ) ¶

The above three functions provide dialogs that prompt the user to enter a value of the desired type.

class tkinter.simpledialog. Dialog ( parent , title = None ) ¶

The base class for custom dialogs.

body ( master ) ¶

Override to construct the dialog’s interface and return the widget that should have initial focus.

buttonbox ( ) ¶

Default behaviour adds OK and Cancel buttons. Override for custom button layouts.

tkinter.filedialog — File selection dialogs¶

The tkinter.filedialog module provides classes and factory functions for creating file/directory selection windows.

Native Load/Save Dialogs¶

The following classes and functions provide file dialog windows that combine a native look-and-feel with configuration options to customize behaviour. The following keyword arguments are applicable to the classes and functions listed below:

Static factory functions

The below functions when called create a modal, native look-and-feel dialog, wait for the user’s selection, then return the selected value(s) or None to the caller.

tkinter.filedialog. askopenfile ( mode = ‘r’ , ** options ) ¶ tkinter.filedialog. askopenfiles ( mode = ‘r’ , ** options ) ¶

The above two functions create an Open dialog and return the opened file object(s) in read-only mode.

tkinter.filedialog. asksaveasfile ( mode = ‘w’ , ** options ) ¶

Create a SaveAs dialog and return a file object opened in write-only mode.

tkinter.filedialog. askopenfilename ( ** options ) ¶ tkinter.filedialog. askopenfilenames ( ** options ) ¶

The above two functions create an Open dialog and return the selected filename(s) that correspond to existing file(s).

tkinter.filedialog. asksaveasfilename ( ** options ) ¶

Create a SaveAs dialog and return the selected filename.

tkinter.filedialog. askdirectory ( ** options ) ¶

class tkinter.filedialog. Open ( master = None , ** options ) ¶ class tkinter.filedialog. SaveAs ( master = None , ** options ) ¶

The above two classes provide native dialog windows for saving and loading files.

Convenience classes

The below classes are used for creating file/directory windows from scratch. These do not emulate the native look-and-feel of the platform.

class tkinter.filedialog. Directory ( master = None , ** options ) ¶

Create a dialog prompting the user to select a directory.

The FileDialog class should be subclassed for custom event handling and behaviour.

Create a basic file selection dialog.

cancel_command ( event = None ) ¶

Trigger the termination of the dialog window.

Event handler for double-click event on directory.

Event handler for click event on directory.

Event handler for double-click event on file.

Event handler for single-click event on file.

filter_command ( event = None ) ¶

Filter the files by directory.

Retrieve the file filter currently in use.

Retrieve the currently selected item.

go ( dir_or_file = os.curdir , pattern = ‘*’ , default = » , key = None ) ¶

Render dialog and start event loop.

Exit dialog returning current selection.

Exit dialog returning filename, if any.

Update the current file selection to file.

class tkinter.filedialog. LoadFileDialog ( master , title = None ) ¶

A subclass of FileDialog that creates a dialog window for selecting an existing file.

Test that a file is provided and that the selection indicates an already existing file.

class tkinter.filedialog. SaveFileDialog ( master , title = None ) ¶

A subclass of FileDialog that creates a dialog window for selecting a destination file.

Test whether or not the selection points to a valid file that is not a directory. Confirmation is required if an already existing file is selected.

tkinter.commondialog — Dialog window templates¶

The tkinter.commondialog module provides the Dialog class that is the base class for dialogs defined in other supporting modules.

class tkinter.commondialog. Dialog ( master = None , ** options ) ¶ show ( color = None , ** options ) ¶

Источник

Читайте также:  Бот на языке python
Оцените статью