#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Для исполнения одного примера задайте его номер
в качестве параметра при запуске программы.
Используйте параметр h или help для просмотра
документации к функциям и классам примеров.
"""

import sys

def pfi():
	"Print function information"
	caller_code = sys._getframe(1).f_code
	example_no = caller_code.co_name[-2:]
	h = '*' * 6
	print('\n       ', h, 'Example', example_no, h)
	print(caller_code.co_consts[0])

def m(s):
	"Print mark at line begin"
	print(s + ' => ', end='')

# Необходимо импортировать модуль tkinter
from tkinter import *

def example_01():
	"""
	Простое приложение, процедурный стиль
	"""
	pfi()

	root = Tk()
	Label(root, text='Simple application').pack()
	Button(root, text='Quit', command=root.destroy).pack()
	root.mainloop()

def example_02():
	"""
	Простое приложение, объекно-ориентированный стиль
	"""
	pfi()

	class Application():
		def __init__(self):
			self.root = Tk()
			Label(self.root, text='Object-style application').pack()
			Button(self.root, text='Quit', command=self.root.destroy).pack()
			self.root.mainloop()
	Application()

def example_03():
	"""
	Большая часть виджетов может быть вызвана без параметров
	"""
	pfi()

	root = Tk()
	Button(root).pack()
	Checkbutton(root).pack()
	Entry(root).pack()
	Frame(root).pack()
	Label(root).pack()
	LabelFrame(root).pack()
	Listbox(root).pack()
	Menubutton(root).pack()
	Message(root).pack()
	PanedWindow(root).pack()
	Radiobutton(root).pack()
	Scale(root).pack()
	Scrollbar(root).pack()
	Spinbox(root).pack()
	Text(root).pack()
	root.mainloop()

def example_04():
	"""
	Менеджер компоновки pack
	"""
	pfi()

	root = Tk()
	root.geometry('480x320')

	# Три фрейма по вертикали
	ftop = Frame(root, bg='blue'); ftop.pack(side=TOP, fill=X)
	fcenter = Frame(root, bg='pink'); fcenter.pack(side=TOP, fill=BOTH, expand=YES)
	fbottom = Frame(root, bg='green'); fbottom.pack(side=BOTTOM, fill=X)

	# Кнопки внутри фреймов
	Button(ftop, text='Top Button').pack(side=LEFT)
	Button(fcenter, text='Left').pack(side=LEFT, anchor=N)
	Button(fcenter, text='Center area').pack(side=LEFT, fill=BOTH, expand=YES)
	Button(fcenter, text='Right').pack(side=RIGHT, anchor=N)
	Button(fbottom, text='Quit', command=root.destroy).pack(side=RIGHT)
	
	root.mainloop()

def example_05():
	"""
	Менеджер компоновки grid
	"""
	pfi()

	root = Tk()
	Label(root, text='Probe Index').grid(row=0, column=0, sticky=W)
	Label(root, text='Probe Description').grid(row=1, column=0, sticky=W)
	Entry(root).grid(row=0, column=1, sticky=W)
	Entry(root).grid(row=1, column=1, sticky=W)
	Button(root, text='Set Index').grid(row=0, column=2, sticky=E)
	Button(root, text='Set Description').grid(row=1, column=2, sticky=E)
	Button(root, text='Quit', command=root.destroy).grid(row=0, column=3, rowspan=5, sticky=NS)
	Text(root).grid(row=2, column=0, columnspan=3, sticky=NSEW)
	Entry(root).grid(row=3, column=0, columnspan=3, sticky=EW)
	Entry(root).grid(row=4, column=1, columnspan=2, sticky=EW)
	root.rowconfigure(2, weight=1)
	root.columnconfigure(1, weight=1)
	root.mainloop()

def example_06():
	"""
	Менеджер компоновки place
	"""
	pfi()

	root = Tk()
	root.geometry('446x60')
	Label(root, text='Probe Index').place(x=10, y=10)
	Label(root, text='Probe Description').place(x=10, y=40)
	Entry(root).place(x=130, y=10)
	Entry(root).place(x=130, y=40)
	Button(root, text='Set Index').place(x=430, y=10, anchor=E)
	Button(root, text='Set Description').place(x=430, y=40, anchor=E)
	root.mainloop()

def example_07():
	"""
	PanedWindow
	"""
	pfi()

	root = Tk()

	w1 = PanedWindow(showhandle=True)
	w1.pack(fill=BOTH, expand=YES)
	
	left = Button(w1, text='Left')
	w1.add(left)

	w2 = PanedWindow(w1, orient=VERTICAL)
	w1.add(w2)

	top = Button(w2, text='Top', width=24)
	w2.add(top)

	bottom = Button(w2, text='Bottom')
	w2.add(bottom)
	
	right = Button(w1, text='Right')
	w1.paneconfigure(right)
	w1.add(right, minsize=120)

	root.mainloop()

def example_08():
	"""
	Radiobutton
	"""
	pfi()

	root = Tk()

	def cb():
		label.config(text='Option %s selected' % str(var.get()))

	var = IntVar()
	Radiobutton(root, text="Option 1", variable=var, value=1, command=cb).pack(anchor=W)
	Radiobutton(root, text="Option 2", variable=var, value=2, command=cb).pack(anchor=W)
	Radiobutton(root, text="Option 3", variable=var, value=3, command=cb).pack(anchor=W)
	label = Label(root, text=' No selection yet  ')
	label.pack()

	root.mainloop()

def example_09():
	"""
	Объекты-переменные, callback
	"""
	pfi()

	root = Tk()
	cbr = lambda *args: print('Read callback')
	cbw = lambda *args: print('Write callback')
	vs = StringVar()
	vs.trace('r', cbr)
	vs.trace('w', cbw)
	m('Before set 1'); vs.set('abc')
	m('Before set 2'); vs.set('abc') # Значение имеет сам вызов set(),
	m('Before get 3'); v = vs.get()  # а не изменение величины
	print('vs = ', v)

def example_10():
	"""
	Привязка переменных к виджетам
	"""
	pfi()

	root = Tk()
	vt = StringVar(value='abc')

	Button(root, textvariable=vt).pack()
	Checkbutton(root, textvariable=vt).pack()
	Entry(root, textvariable=vt).pack()
	Label(root, textvariable=vt).pack()
	Listbox(root, listvariable=vt).pack()
	Menubutton(root, textvariable=vt).pack()
	Message(root, textvariable=vt).pack()
	Radiobutton(root, textvariable=vt).pack()
	Scale(root, variable=vt).pack()
	Spinbox(root, textvariable=vt).pack()
	OptionMenu(root, variable=vt, value=33).pack()

	root.mainloop()

def example_11():
	"""
	Окна сообщений
	"""
	pfi()

	from tkinter import messagebox

	messagebox.showinfo("showinfo", "Info message")
	messagebox.showwarning("showwarning", "Warning message")
	messagebox.showerror("showerror", "Error message")
	result = messagebox.askyesno("ashyesno", "Yes or No")
	print(result)
	result = messagebox.askokcancel("ashokcancle", "Is it OK?")
	print(result)
	result = messagebox.askyesnocancel("askyesnocancel", "Yes, No or Cancel")
	print(result)
	result = messagebox.askretrycancel("askyesnocancel", "Retry or Cancel")
	print(result)

def example_12():
	"""
	Простые диалоги
	"""
	pfi()

	from tkinter import simpledialog
	root = Tk()

	result = simpledialog.askstring("askstring", "Enter string")
	print(result)
	result = simpledialog.askinteger("askinteger", "Enter integer number")
	print(result)
	result = simpledialog.askfloat("askfloat", "Enter float number")
	print(result)

def example_13():
	"""
	Диалоги выбора файла
	"""
	pfi()

	root = Tk()

	from tkinter import filedialog
	filename = filedialog.askopenfilename()
	print('Selected file:', filename, len(filename), 'bytes', filename.__class__)
	filename = filedialog.asksaveasfilename()
	print('Selected file:', filename, len(filename), 'bytes', filename.__class__)
	filename = filedialog.askdirectory()
	print('Selected file:', filename, len(filename), 'bytes', filename.__class__)

def example_14():
	"""
	Диалог выбора цвета
	"""
	pfi()

	root = Tk()
	from tkinter import colorchooser
	result = colorchooser.askcolor()
	print(result)

def example_15():
	"""
	Редактор текста со скролл-баром
	"""
	pfi()

	from tkinter import scrolledtext
	root = Tk()
	scrolledtext.ScrolledText().pack(fill=BOTH, expand=YES)
	root.mainloop()

def example_16():
	"""
	Аргумент command
	"""
	pfi()

	def cb(*args):
		print('cb', *args, end=', ', flush=True)

	root = Tk()
	vt = StringVar()
	f = Frame(root).pack()
	
	# Виджеты воспринимающие аргумент command
	Scrollbar(root, command=cb).pack(side=RIGHT, fill=Y)
	Button(f, command=cb).pack()
	Checkbutton(f, command=cb).pack()
	Radiobutton(f, command=cb).pack()
	Scale(f, command=cb, orient=HORIZONTAL).pack(fill=BOTH)
	Spinbox(f, textvariable=vt, values=('ab', 'cd', 'ef', 'gh'), command=cb).pack()

	Label(root, textvariable=vt).pack()
	root.mainloop()

def example_17():
	"""
	Субмодуль ttk
	"""
	pfi()

	root = Tk()
	from tkinter import ttk
	
	style = ttk.Style()
	style.configure('TButton', foreground="red", background="yellow")
	style.configure('TLabel', foreground="green")
	ttk.Label(root, text='Styled Application').pack(padx=4, pady=8)
	ttk.Combobox(root, values=('ab', 'cd', 'ef', 'gh')).pack()
	ttk.Progressbar(root).pack()
	ttk.Notebook(root).pack()
	ttk.Separator(root).pack()
	ttk.Treeview(root).pack()
	ttk.Button(root, text='Quit', command=root.destroy).pack()
	ttk.Sizegrip(root).pack(side=RIGHT, anchor=S)

	root.mainloop()

def example_18():
	"""
	Субмодуль tix, аргумент command
	"""
	pfi()

	from tkinter import tix
	root = tix.Tk()

	def cmd(value):
		print('Selected value', value)
	
	w = tix.ComboBox(root, value='ab', command=cmd); w.pack()
	for item in 'ab', 'cd', 'ef', 'gh':
		w.insert(tix.END, item)

	root.mainloop()

def example_19():
	"""
	Субмодуль tix, привязка виджета к переменной,
	редактирование разрешено"
	"""
	pfi()

	from tkinter import tix
	root = tix.Tk()

	vt = StringVar()
	vt.trace("w", lambda *args: print('Selected value', vt.get()))
	vt.set('ab')
	w = tix.ComboBox(root, editable=1, variable=vt); w.pack()
	for item in 'ab', 'cd', 'ef', 'gh':
		w.insert(tix.END, item)

	root.mainloop()

def example_20():
	"""
	Установка callback
	"""
	pfi()

	def on_run():
		print('Run button clicked')

	root = Tk()
	Button(root, text='Run', command=on_run).pack()
	Button(root, text='Quit', command=root.destroy).pack()
	root.mainloop()

def example_21():
	"""
	Callback как метод класса
	"""
	pfi()

	class Application():
		def __init__(self):
			self.root = Tk()
			Button(self.root, text='Run', command=self.on_run).pack()
			Button(self.root, text='Quit', command=self.root.destroy).pack()
			self.root.mainloop()
		def on_run(self):
			print('Run button clicked')

	Application()

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def example_22():
	"""
	Взаимодействие с библиотекой matplotlib
	"""
	pfi()

	xa = np.linspace(-np.pi, np.pi, 101, endpoint=True)
	ya = np.sin(xa)

	def update():
		nonlocal ya
		ya *= 0.9
		axes.plot(xa, ya, color='blue')
		fig.canvas.draw()

	fig = plt.Figure(figsize=(6, 4))
	axes = fig.add_subplot(1, 1, 1)
	axes.plot(xa, ya, color='red')

	root = Tk()
	canvas = FigureCanvasTkAgg(fig, master=root)
	canvas._tkcanvas.pack(fill=BOTH, expand=YES)
	frame = Frame(root) ; frame.pack()
	Button(frame, text='Update', command=update).pack(side=LEFT)
	Button(frame, text='Quit', command=root.destroy).pack(side=RIGHT)
	root.mainloop()

if len(sys.argv) > 1:
	if sys.argv[1].isdigit() and int(sys.argv[1]) > 0:
		exec('example_%02d()' % int(sys.argv[1]))
	elif sys.argv[1][0].lower() == 'h':
		help(__name__)
	else:
		print(__doc__)
else:
	tuple(map(lambda c: exec(c + '()'),
		(f for f in sys._getframe().f_code.co_names
			if f.startswith('example_'))))
