This commit is contained in:
Pascal Engélibert 2024-10-29 18:28:39 +01:00
commit 2b71586c04
8 changed files with 880 additions and 17 deletions

View file

@ -1,6 +1,6 @@
https://code.activestate.com/recipes/579048-python-mandelbrot-fractal-with-tkinter/
https://stackoverflow.com/questions/9886274/how-can-i-convert-canvas-content-to-an-image
https://tkdocs.com/tutorial/text.html
https://stackoverflow.com/questions/33084097/tkinter-really-all-complete-event-list
https://stackoverflow.com/questions/4172659/master-list-of-all-tkinter-events
https://www.tcl.tk/man/tcl8.5/TkCmd/bind.htm#M7
* https://code.activestate.com/recipes/579048-python-mandelbrot-fractal-with-tkinter/
* https://stackoverflow.com/questions/9886274/how-can-i-convert-canvas-content-to-an-image
* https://tkdocs.com/tutorial/text.html
* https://stackoverflow.com/questions/33084097/tkinter-really-all-complete-event-list
* https://stackoverflow.com/questions/4172659/master-list-of-all-tkinter-events
* https://www.tcl.tk/man/tcl8.5/TkCmd/bind.htm#M7

100
editor.py
View file

@ -1,32 +1,111 @@
import network
import tkinter as tk
from tkinter import ttk, filedialog, colorchooser
import sys
listen_addr = ("0.0.0.0", int(sys.argv[1]))
send_addr = ("192.168.0.255", int(sys.argv[2]))
send_addr = ("192.168.1.255", int(sys.argv[2]))
sock = network.Sock()
waiting_for_text = True
root = tk.Tk()
area = tk.Text()
area.pack()
def foo():
print("foo")
root.option_add('*tearOff', False)
menubar = tk.Menu(root)
root['menu'] = menubar
menu_file = tk.Menu(menubar)
menu_edit = tk.Menu(menubar)
menubar.add_cascade(menu=menu_file, label='File')
menubar.add_cascade(menu=menu_edit, label='Edit')
menu_file.add_command(label='New', command=foo)
area = tk.Text(root)
area.grid(column=0, row=1, sticky=(tk.N, tk.S, tk.E, tk.W))
area_scrolly = ttk.Scrollbar(root, orient=tk.VERTICAL, command=area.yview)
area_scrolly.grid(column=1, row=1, sticky=(tk.N, tk.S, tk.E, tk.W))
area.configure(yscrollcommand=area_scrolly.set)
canvas = tk.Canvas(root, background='white')
canvas.grid(column=2, row=1, sticky=(tk.N, tk.S, tk.E, tk.W))
canvas_last_x = 0
canvas_last_y = 0
def canvas_save_pos(event):
global canvas_last_x, canvas_last_y
canvas_last_x = event.x
canvas_last_y = event.y
def canvas_move(event):
canvas.create_line(canvas_last_x, canvas_last_y, event.x, event.y)
sock.send({"type":"create_line", "x1":canvas_last_x, "y1":canvas_last_y, "x2":event.x, "y2":event.y}, send_addr)
canvas_save_pos(event)
def canvas_click(event):
print(colorchooser.askcolor(initialcolor='black'))
canvas.bind("<Button-1>", canvas_save_pos)
canvas.bind("<B1-Motion>", canvas_move)
canvas.bind("<Button-3>", canvas_click)
root.rowconfigure(1, weight=1)
root.columnconfigure(0, weight=1)
root.columnconfigure(2, weight=1)
def on_save_bt():
path = tk.filedialog.asksaveasfilename(filetypes=[("Fichier texte", ".txt")])
file = open(path, "w")
file.write(area.get("1.0", "end"))
toolbar = ttk.Frame(root)
toolbar.grid(column=0, row=0, columnspan=2, sticky=(tk.N, tk.S, tk.E, tk.W))
save_bt = ttk.Button(toolbar, text="Enregistrer", command=on_save_bt)
save_bt.grid(column=0, row=0, sticky=(tk.W))
open_bt = ttk.Button(toolbar, text="Ouvrir")
open_bt.grid(column=1, row=0, sticky=(tk.W))
def diff(old, new):
index = 0
if len(old) > len(new):
for i in range(len()):
pass
line = 1
char = 0
for i in range(min(len(old), len(new))):
if old[i] != new[i]:
return {
"type": "replace",
"start": str(line)+"."+str(char),
"end": 0,
"text": new[i:i+abs(len(old)-len(new))]
}
char += 1
if old[i] == "\n":
line += 1
char = 0
return {
"type": "insert",
"start": "end",
"text": new[i:i+abs(len(old)-len(new))]
}
def area_input(event):
def on_area_input(event):
#print(area.get("1.0", "end"))
print(event)
sock.send({"type":"insert", "start":"1.0", "text":area.get("1.0", "end")}, send_addr)
#sock.send({"type":"insert", "start":"1.0", "text":area.get("1.0", "end")}, send_addr)
sock.send({"type":"replace", "start":"1.0", "end":"end", "text":area.get("1.0", "end")}, send_addr)
#if event.keycode == 25:
# area.mark_set("insert", "1.0")
area.bind("<KeyRelease>", on_area_input)
area.bind("<B3-Motion>", on_area_input)
def on_request(r):
global waiting_for_text
print(r)
@ -41,9 +120,8 @@ def on_request(r):
area.replace(c["start"], c["end"], c["text"])
elif c["type"] == "get":
sock.send({"type":"set", "text":area.get("1.0", "end")}, send_addr)
area.insert("1.0", r[1])
area.bind("<KeyRelease>", area_input)
elif c["type"] == "create_line":
canvas.create_line(c["x1"], c["y1"], c["x2"], c["y2"])
sock.listen(listen_addr, on_request)

7
makefile Executable file
View file

@ -0,0 +1,7 @@
all: tutorial.pdf
tutorial.pdf: tutorial.html
wkhtmltopdf -s A4 --footer-center "[page] / [topage]" --footer-font-name "Libertinus Sans" --footer-font-size 11 --header-left "[subsection]" --header-right "[title]" --header-font-name "Libertinus Sans" --header-font-size 11 --margin-top 20mm --footer-spacing 7 --header-spacing 7 --margin-bottom 20mm tutorial.html tutorial.pdf
tutorial.html: tutorial.md tutorial-head.html
pandoc tutorial.md -o tutorial.html --self-contained -M title="Tutoriel Tkinter" --highlight-style pygments -H tutorial-head.html || exit 1

21
skeleton.py Normal file
View file

@ -0,0 +1,21 @@
import network
import tkinter as tk
from tkinter import ttk
import sys
listen_addr = ("0.0.0.0", 4444)
send_addr = ("192.168.1.255", 4444)
sock = network.Sock()
root = tk.Tk()
def on_request(r):
c, a = r
print(c, a)
sock.listen(listen_addr, on_request)
sock.send({"message":"bonjour"}, send_addr)
root.mainloop()

33
tutorial-head.html Normal file
View file

@ -0,0 +1,33 @@
<style type="text/css">
body {
font-family: "Libertinus Sans";
max-width: 80% !important;
font-size: 13pt !important;
}
h2 {
border-bottom: 2pt solid black;
}
h3 {
border-bottom: 1pt solid black;
}
h4 {
border-bottom: 1pt solid #ccc;
}
div.sourceCode {
margin-left: -5px;
border-left: 1px dashed #ccc;
padding-left: 4px;
}
div.sourceCode code {
font-size: 10pt !important;
}
code {
font-family: "Fira Code" !important;
}
p code {
padding-left: 4px;
}
header {
margin-top: 1cm;
}
</style>

452
tutorial.html Normal file
View file

@ -0,0 +1,452 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang xml:lang>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>Tutoriel Tkinter</title>
<style>
html {
line-height: 1.5;
font-family: Georgia, serif;
font-size: 20px;
color: #1a1a1a;
background-color: #fdfdfd;
}
body {
margin: 0 auto;
max-width: 36em;
padding-left: 50px;
padding-right: 50px;
padding-top: 50px;
padding-bottom: 50px;
hyphens: auto;
overflow-wrap: break-word;
text-rendering: optimizeLegibility;
font-kerning: normal;
}
@media (max-width: 600px) {
body {
font-size: 0.9em;
padding: 1em;
}
h1 {
font-size: 1.8em;
}
}
@media print {
body {
background-color: transparent;
color: black;
font-size: 12pt;
}
p, h2, h3 {
orphans: 3;
widows: 3;
}
h2, h3, h4 {
page-break-after: avoid;
}
}
p {
margin: 1em 0;
}
a {
color: #1a1a1a;
}
a:visited {
color: #1a1a1a;
}
img {
max-width: 100%;
}
h1, h2, h3, h4, h5, h6 {
margin-top: 1.4em;
}
h5, h6 {
font-size: 1em;
font-style: italic;
}
h6 {
font-weight: normal;
}
ol, ul {
padding-left: 1.7em;
margin-top: 1em;
}
li > ol, li > ul {
margin-top: 0;
}
blockquote {
margin: 1em 0 1em 1.7em;
padding-left: 1em;
border-left: 2px solid #e6e6e6;
color: #606060;
}
code {
font-family: Menlo, Monaco, 'Lucida Console', Consolas, monospace;
font-size: 85%;
margin: 0;
}
pre {
margin: 1em 0;
overflow: auto;
}
pre code {
padding: 0;
overflow: visible;
overflow-wrap: normal;
}
.sourceCode {
background-color: transparent;
overflow: visible;
}
hr {
background-color: #1a1a1a;
border: none;
height: 1px;
margin: 1em 0;
}
table {
margin: 1em 0;
border-collapse: collapse;
width: 100%;
overflow-x: auto;
display: block;
font-variant-numeric: lining-nums tabular-nums;
}
table caption {
margin-bottom: 0.75em;
}
tbody {
margin-top: 0.5em;
border-top: 1px solid #1a1a1a;
border-bottom: 1px solid #1a1a1a;
}
th {
border-top: 1px solid #1a1a1a;
padding: 0.25em 0.5em 0.25em 0.5em;
}
td {
padding: 0.125em 0.5em 0.25em 0.5em;
}
header {
margin-bottom: 4em;
text-align: center;
}
#TOC li {
list-style: none;
}
#TOC ul {
padding-left: 1.3em;
}
#TOC > ul {
padding-left: 0;
}
#TOC a:not(:hover) {
text-decoration: none;
}
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { color: #008000; } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { color: #008000; font-weight: bold; } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
.display.math{display: block; text-align: center; margin: 0.5rem auto;}
</style>
<style type="text/css">
body {
font-family: "Libertinus Sans";
max-width: 80% !important;
font-size: 13pt !important;
}
h2 {
border-bottom: 2pt solid black;
}
h3 {
border-bottom: 1pt solid black;
}
h4 {
border-bottom: 1pt solid #ccc;
}
div.sourceCode {
margin-left: -5px;
border-left: 1px dashed #ccc;
padding-left: 4px;
}
div.sourceCode code {
font-size: 10pt !important;
}
code {
font-family: "Fira Code" !important;
}
p code {
padding-left: 4px;
}
header {
margin-top: 1cm;
}
</style>
</head>
<body>
<header id="title-block-header">
<h1 class="title">Tutoriel Tkinter</h1>
</header>
<h1 id="tutoriel-tkinter">Tutoriel Tkinter</h1>
<p>Pour aller plus loin : <a href="https://tkdocs.com/tutorial/index.html">TkDocs Tutorial</a></p>
<h2 id="code-de-base">Code de base</h2>
<p>Créer une fenêtre vide :</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> tkinter <span class="im">as</span> tk</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tkinter <span class="im">import</span> ttk</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>root <span class="op">=</span> tk.Tk()</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>root.mainloop()</span></code></pre></div>
<p>Ajouter des boutons dans la fenêtre :</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> tkinter <span class="im">as</span> tk</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tkinter <span class="im">import</span> ttk</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>root <span class="op">=</span> tk.Tk()</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>bt1 <span class="op">=</span> ttk.Button(root, text<span class="op">=</span><span class="st">&quot;Bonjour&quot;</span>)</span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a>bt1.grid(column<span class="op">=</span><span class="dv">0</span>, row<span class="op">=</span><span class="dv">0</span>)</span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a>bt2 <span class="op">=</span> ttk.Button(root, text<span class="op">=</span><span class="st">&quot;Au revoir&quot;</span>)</span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a>bt2.grid(column<span class="op">=</span><span class="dv">1</span>, row<span class="op">=</span><span class="dv">0</span>)</span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a>root.mainloop()</span></code></pre></div>
<h3 id="positionnement">Positionnement</h3>
<p>On peut changer le nombre de colonnes ou de lignes occupées par un
widget en ajoutant les paramètres <code>columnspan</code> ou
<code>rowspan</code> en plus de <code>column</code> et
<code>row</code>.</p>
<p>Pour coller un widget au bord de la grille, on peut ajouter
<code>sticky</code> :</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>bt2.grid(column<span class="op">=</span><span class="dv">1</span>, row<span class="op">=</span><span class="dv">0</span>, sticky<span class="op">=</span>(tk.W, tk.N))</span></code></pre></div>
<p><code>sticky</code> prend une liste de 0 à 4 éléments parmi :</p>
<ul>
<li><code>tk.E</code> : <em>East</em> = droite</li>
<li><code>tk.N</code> : <em>North</em> = haut</li>
<li><code>tk.S</code> : <em>South</em> = bas</li>
<li><code>tk.W</code> : <em>West</em> = gauche</li>
</ul>
<h3 id="redimensionner-la-fenêtre">Redimensionner la fenêtre</h3>
<p>Il faut indiquer quelles lignes et colonnes doivent changer de taille
quand la fenêtre change de taille.</p>
<p>Dans cet exemple, ce sont la ligne 1 et la colonne 0.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>root.rowconfigure(<span class="dv">1</span>, weight<span class="op">=</span><span class="dv">1</span>)</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>root.columnconfigure(<span class="dv">0</span>, weight<span class="op">=</span><span class="dv">1</span>)</span></code></pre></div>
<p>On peut appeler plusieurs fois ces fonctions pour choisir plusieurs
lignes et colonnes, et changer les <code>weight</code> pour modifier les
proportions.</p>
<h2 id="widgets">Widgets</h2>
<p>Tous les widgets peuvent être positionnés avec <code>grid</code>, de
la même manière que ci-dessus.</p>
<h3 id="label">Label</h3>
<p>Juste du texte.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>label <span class="op">=</span> ttk.Label(root, text<span class="op">=</span><span class="st">&quot;Je suis un texte. Wow.&quot;</span>)</span></code></pre></div>
<p>On peut aussi modifier le texte plus tard :</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>label_text <span class="op">=</span> tk.StringVar()</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>label[<span class="st">&quot;textvariable&quot;</span>] <span class="op">=</span> label_text</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>label_text.<span class="bu">set</span>(<span class="st">&quot;Le nouveau texte. Tout ça pour ça !&quot;</span>)</span></code></pre></div>
<h3 id="bouton">Bouton</h3>
<p>Un bouton quon peut cliquer.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> onclick():</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">&quot;On a cliqué&quot;</span>)</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>bt <span class="op">=</span> ttk.Button(root, text<span class="op">=</span><span class="st">&quot;Cliquez-moi&quot;</span>, command<span class="op">=</span>onclick)</span></code></pre></div>
<h3 id="image">Image</h3>
<p>Un bouton ou un label peut afficher une image :</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>img <span class="op">=</span> tk.PhotoImage(<span class="bu">file</span><span class="op">=</span><span class="st">&#39;image.png&#39;</span>)</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>label[<span class="st">&quot;image&quot;</span>] <span class="op">=</span> img</span></code></pre></div>
<h3 id="entrée-de-texte">Entrée de texte</h3>
<p>Boîte dans laquelle on peut écrire une ligne de texte.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>text <span class="op">=</span> tk.StringVar()</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>entry <span class="op">=</span> ttk.Entry(root, textvariable<span class="op">=</span>text)</span></code></pre></div>
<p>Plus tard, on peut récupérer le texte :</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">&quot;L&#39;utilisateur a écrit :&quot;</span>, text.get())</span></code></pre></div>
<h3 id="entrée-de-texte-multiligne">Entrée de texte multiligne</h3>
<p>Zone dans laquelle on peut écrire du texte en plusieurs lignes.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>text <span class="op">=</span> tk.Text(root)</span></code></pre></div>
<p>Il y a plusieurs méthodes pour interagir avec le texte :</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(area.get(<span class="st">&quot;1.0&quot;</span>, <span class="st">&quot;end&quot;</span>)) <span class="co"># obtenir tout le texte</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(area.get(<span class="st">&quot;2.0&quot;</span>, <span class="st">&quot;8.0&quot;</span>)) <span class="co"># le texte de la ligne 2 à la ligne 8</span></span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>area.replace(<span class="st">&quot;1.0&quot;</span>, <span class="st">&quot;end&quot;</span>, <span class="st">&quot;le nouveau texte&quot;</span>) <span class="co"># remplacer du texte</span></span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>area.insert(<span class="st">&quot;1.0&quot;</span>, <span class="st">&quot;le nouveau texte&quot;</span>) <span class="co"># insérer du texte</span></span></code></pre></div>
<h3 id="barre-de-défilement">Barre de défilement</h3>
<p>Certains widgets (<code>Text</code>) peuvent défiler avec la molette,
mais pour afficher la barre de défilement il faut un widget
supplémentaire.</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>scroll <span class="op">=</span> ttk.Scrollbar(root, orient<span class="op">=</span>tk.VERTICAL, command<span class="op">=</span>mon_widget_qui_défile.yview)</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>scroll.grid(column<span class="op">=</span><span class="dv">1</span>, row<span class="op">=</span><span class="dv">0</span>, sticky<span class="op">=</span>(tk.N, tk.S, tk.E, tk.W))</span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a>mon_widget_qui_défile.configure(yscrollcommand<span class="op">=</span>scroll.<span class="bu">set</span>)</span></code></pre></div>
<h3 id="cadre">Cadre</h3>
<p>Un cadre qui peut avoir une bordure et contenir dautres widgets.</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a>frame <span class="op">=</span> ttk.Frame(root, borderwidth<span class="op">=</span><span class="dv">5</span>, relief<span class="op">=</span><span class="st">&quot;ridge&quot;</span>, width<span class="op">=</span><span class="dv">200</span>, height<span class="op">=</span><span class="dv">100</span>)</span></code></pre></div>
<p>Les options ne sont pas obligatoires.</p>
<p>Le cadre contient ses propres lignes et colonnes. Pour placer des
widgets dedans, il suffit de remplacer <code>root</code> par
<code>frame</code> en les créant.</p>
<h3 id="barre-de-menus">Barre de menus</h3>
<p>La barre de menus en haut de la fenêtre.</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>root.option_add(<span class="st">&#39;*tearOff&#39;</span>, <span class="va">False</span>)</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>menubar <span class="op">=</span> tk.Menu(root)</span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>root[<span class="st">&#39;menu&#39;</span>] <span class="op">=</span> menubar</span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a>menu_file <span class="op">=</span> tk.Menu(menubar)</span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a>menu_edit <span class="op">=</span> tk.Menu(menubar)</span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a>menubar.add_cascade(menu<span class="op">=</span>menu_file, label<span class="op">=</span><span class="st">&#39;Fichier&#39;</span>)</span>
<span id="cb15-9"><a href="#cb15-9" aria-hidden="true" tabindex="-1"></a>menubar.add_cascade(menu<span class="op">=</span>menu_edit, label<span class="op">=</span><span class="st">&#39;Édition&#39;</span>)</span>
<span id="cb15-10"><a href="#cb15-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-11"><a href="#cb15-11" aria-hidden="true" tabindex="-1"></a>menu_file.add_command(label<span class="op">=</span><span class="st">&#39;Ouvrir&#39;</span>, command<span class="op">=</span>on_open)</span></code></pre></div>
<h3 id="canevas">Canevas</h3>
<p>Le canevas est une zone de dessin.</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>canvas <span class="op">=</span> tk.Canvas(root, background<span class="op">=</span><span class="st">&#39;white&#39;</span>)</span></code></pre></div>
<p>On peut y dessiner des formes :</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>canvas.create_line(x1, y1, x2, y2)</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>canvas.create_line(x1, y1, x2, y2, fill<span class="op">=</span><span class="st">&quot;red&quot;</span>, width<span class="op">=</span><span class="dv">3</span>, dash<span class="op">=</span><span class="dv">6</span>)</span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a>canvas.create_rectangle(x1, y1, x2, y2, fill<span class="op">=</span><span class="st">&quot;red&quot;</span>, outline<span class="op">=</span><span class="st">&quot;blue&quot;</span>)</span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a>canvas.create_oval(x1, y1, x2, y2, fill<span class="op">=</span><span class="st">&quot;red&quot;</span>, outline<span class="op">=</span><span class="st">&quot;blue&quot;</span>)</span></code></pre></div>
<h2 id="événements">Événements</h2>
<p>Quand il se passe quelque chose sur un widget, un événement est
généré. On peut écouter les événements de certains types, cest-à-dire
lancer une fonction quand laction se produit.</p>
<p>Par exemple, on affiche des informations quand une touche du clavier
est relâchée dans la zone de texte :</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a>text <span class="op">=</span> tk.Text(root)</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> onrelease(event):</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">&quot;On a frappé le clavier !&quot;</span>)</span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(event)</span>
<span id="cb18-6"><a href="#cb18-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-7"><a href="#cb18-7" aria-hidden="true" tabindex="-1"></a>area.bind(<span class="st">&quot;&lt;KeyRelease&gt;&quot;</span>, onrelease)</span></code></pre></div>
<p>On peut aussi utiliser les infos contenues dans lévénement, par
exemple <code>event.keycode</code>.</p>
<h3 id="liste-des-événements">Liste des événements</h3>
<ul>
<li>Souris
<ul>
<li><code>ButtonPress</code>: clic enfoncé dun bouton de la souris</li>
<li><code>Button-1</code>: comme <code>ButtonPress</code> mais seulement
pour le clic gauche</li>
<li><code>Button-2</code>: comme <code>ButtonPress</code> mais seulement
pour le clic molette</li>
<li><code>Button-3</code>: comme <code>ButtonPress</code> mais seulement
pour le clic droit</li>
<li><code>ButtonRelease</code>: clic relâché dun bouton de la
souris</li>
<li><code>Double-1</code>: double-clic gauche</li>
<li><code>Double-3</code>: double-clic droit</li>
<li><code>Enter</code>: le pointeur de la souris entre</li>
<li><code>Leave</code>: le pointeur de la souris sort</li>
<li><code>Motion</code>: le pointeur de la souris bouge dedans</li>
<li><code>B1-Motion</code>: comme <code>Motion</code> mais avec le clic
gauche enfoncé</li>
<li><code>B2-Motion</code>: comme <code>Motion</code> mais avec le clic
molette enfoncé</li>
<li><code>B3-Motion</code>: comme <code>Motion</code> mais avec le clic
droit enfoncé</li>
</ul></li>
<li>Clavier
<ul>
<li><code>KeyPress</code>: appui dune touche du clavier</li>
<li><code>KeyRelease</code>: relâche dune touche du clavier</li>
</ul></li>
<li>Widget
<ul>
<li><code>Configure</code>: le widget est créé</li>
<li><code>Expose</code>: le widget est affiché ou réaffiché</li>
<li><code>FocusIn</code>: le widget reçoit le focus</li>
<li><code>FocusOut</code>: le widget pert le focus</li>
</ul></li>
</ul>
<h2 id="dialogues">Dialogues</h2>
<p>On peut ouvrir des fenêtres pour dire ou demander des choses.</p>
<h3 id="fichiers">Fichiers</h3>
<p>Demander où enregistrer un fichier, quel fichier ouvrir, choisir un
dossier.</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tkinter <span class="im">import</span> filedialog</span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a>filetypes <span class="op">=</span> [</span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a> (<span class="st">&quot;Texte&quot;</span>, <span class="st">&quot;*.txt&quot;</span>),</span>
<span id="cb19-5"><a href="#cb19-5" aria-hidden="true" tabindex="-1"></a> (<span class="st">&quot;Image PNG&quot;</span>, <span class="st">&quot;*.png&quot;</span>),</span>
<span id="cb19-6"><a href="#cb19-6" aria-hidden="true" tabindex="-1"></a> (<span class="st">&quot;Autre&quot;</span>, <span class="st">&quot;*.*&quot;</span>)</span>
<span id="cb19-7"><a href="#cb19-7" aria-hidden="true" tabindex="-1"></a>]</span>
<span id="cb19-8"><a href="#cb19-8" aria-hidden="true" tabindex="-1"></a>chemin <span class="op">=</span> tk.filedialog.asksaveasfilename(filetypes<span class="op">=</span>filetypes)</span>
<span id="cb19-9"><a href="#cb19-9" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(chemin)</span></code></pre></div>
<p>On peut remplacer <code>asksaveasfilename</code> par
<code>askopenfilename</code> ou <code>askdirectory</code>.</p>
<h3 id="couleur">Couleur</h3>
<p>Demander de choisir une couleur.</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tkinter <span class="im">import</span> colorchooser</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a>color <span class="op">=</span> colorchooser.askcolor(initialcolor<span class="op">=</span><span class="st">&#39;black&#39;</span>)</span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(color)</span></code></pre></div>
<p>On peut aussi indiquer la couleur initiale avec sa notation
hexadécimale <code>&quot;#000000&quot;</code>.</p>
</body>
</html>

272
tutorial.md Normal file
View file

@ -0,0 +1,272 @@
# Tutoriel Tkinter
Pour aller plus loin : [TkDocs Tutorial](https://tkdocs.com/tutorial/index.html)
## Code de base
Créer une fenêtre vide :
```python
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.mainloop()
```
Ajouter des boutons dans la fenêtre :
```python
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
bt1 = ttk.Button(root, text="Bonjour")
bt1.grid(column=0, row=0)
bt2 = ttk.Button(root, text="Au revoir")
bt2.grid(column=1, row=0)
root.mainloop()
```
### Positionnement
On peut changer le nombre de colonnes ou de lignes occupées par un widget en ajoutant les paramètres `columnspan` ou `rowspan` en plus de `column` et `row`.
Pour coller un widget au bord de la grille, on peut ajouter `sticky` :
```python
bt2.grid(column=1, row=0, sticky=(tk.W, tk.N))
```
`sticky` prend une liste de 0 à 4 éléments parmi :
* `tk.E` : _East_ = droite
* `tk.N` : _North_ = haut
* `tk.S` : _South_ = bas
* `tk.W` : _West_ = gauche
### Redimensionner la fenêtre
Il faut indiquer quelles lignes et colonnes doivent changer de taille quand la fenêtre change de taille.
Dans cet exemple, ce sont la ligne 1 et la colonne 0.
```python
root.rowconfigure(1, weight=1)
root.columnconfigure(0, weight=1)
```
On peut appeler plusieurs fois ces fonctions pour choisir plusieurs lignes et colonnes, et changer les `weight` pour modifier les proportions.
## Widgets
Tous les widgets peuvent être positionnés avec `grid`, de la même manière que ci-dessus.
### Label
Juste du texte.
```python
label = ttk.Label(root, text="Je suis un texte. Wow.")
```
On peut aussi modifier le texte plus tard :
```python
label_text = tk.StringVar()
label["textvariable"] = label_text
label_text.set("Le nouveau texte. Tout ça pour ça !")
```
### Bouton
Un bouton qu'on peut cliquer.
```python
def onclick():
print("On a cliqué")
bt = ttk.Button(root, text="Cliquez-moi", command=onclick)
```
### Image
Un bouton ou un label peut afficher une image :
```python
img = tk.PhotoImage(file='image.png')
label["image"] = img
```
### Entrée de texte
Boîte dans laquelle on peut écrire une ligne de texte.
```python
text = tk.StringVar()
entry = ttk.Entry(root, textvariable=text)
```
Plus tard, on peut récupérer le texte :
```python
print("L'utilisateur a écrit :", text.get())
```
### Entrée de texte multiligne
Zone dans laquelle on peut écrire du texte en plusieurs lignes.
```python
text = tk.Text(root)
```
Il y a plusieurs méthodes pour interagir avec le texte :
```python
print(area.get("1.0", "end")) # obtenir tout le texte
print(area.get("2.0", "8.0")) # le texte de la ligne 2 à la ligne 8
area.replace("1.0", "end", "le nouveau texte") # remplacer du texte
area.insert("1.0", "le nouveau texte") # insérer du texte
```
### Barre de défilement
Certains widgets (`Text`) peuvent défiler avec la molette, mais pour afficher la barre de défilement il faut un widget supplémentaire.
```python
scroll = ttk.Scrollbar(root, orient=tk.VERTICAL, command=mon_widget_qui_défile.yview)
scroll.grid(column=1, row=0, sticky=(tk.N, tk.S, tk.E, tk.W))
mon_widget_qui_défile.configure(yscrollcommand=scroll.set)
```
### Cadre
Un cadre qui peut avoir une bordure et contenir d'autres widgets.
```python
frame = ttk.Frame(root, borderwidth=5, relief="ridge", width=200, height=100)
```
Les options ne sont pas obligatoires.
Le cadre contient ses propres lignes et colonnes.
Pour placer des widgets dedans, il suffit de remplacer `root` par `frame` en les créant.
### Barre de menus
La barre de menus en haut de la fenêtre.
```python
root.option_add('*tearOff', False)
menubar = tk.Menu(root)
root['menu'] = menubar
menu_file = tk.Menu(menubar)
menu_edit = tk.Menu(menubar)
menubar.add_cascade(menu=menu_file, label='Fichier')
menubar.add_cascade(menu=menu_edit, label='Édition')
menu_file.add_command(label='Ouvrir', command=on_open)
```
### Canevas
Le canevas est une zone de dessin.
```python
canvas = tk.Canvas(root, background='white')
```
On peut y dessiner des formes :
```python
canvas.create_line(x1, y1, x2, y2)
canvas.create_line(x1, y1, x2, y2, fill="red", width=3, dash=6)
canvas.create_rectangle(x1, y1, x2, y2, fill="red", outline="blue")
canvas.create_oval(x1, y1, x2, y2, fill="red", outline="blue")
```
## Événements
Quand il se passe quelque chose sur un widget, un événement est généré.
On peut écouter les événements de certains types, c'est-à-dire lancer une fonction quand l'action se produit.
Par exemple, on affiche des informations quand une touche du clavier est relâchée dans la zone de texte :
```python
text = tk.Text(root)
def onrelease(event):
print("On a frappé le clavier !")
print(event)
area.bind("<KeyRelease>", onrelease)
```
On peut aussi utiliser les infos contenues dans l'événement, par exemple `event.keycode`.
### Liste des événements
* Souris
* `ButtonPress`: clic enfoncé d'un bouton de la souris
* `Button-1`: comme `ButtonPress` mais seulement pour le clic gauche
* `Button-2`: comme `ButtonPress` mais seulement pour le clic molette
* `Button-3`: comme `ButtonPress` mais seulement pour le clic droit
* `ButtonRelease`: clic relâché d'un bouton de la souris
* `Double-1`: double-clic gauche
* `Double-3`: double-clic droit
* `Enter`: le pointeur de la souris entre
* `Leave`: le pointeur de la souris sort
* `Motion`: le pointeur de la souris bouge dedans
* `B1-Motion`: comme `Motion` mais avec le clic gauche enfoncé
* `B2-Motion`: comme `Motion` mais avec le clic molette enfoncé
* `B3-Motion`: comme `Motion` mais avec le clic droit enfoncé
* Clavier
* `KeyPress`: appui d'une touche du clavier
* `KeyRelease`: relâche d'une touche du clavier
* Widget
* `Configure`: le widget est créé
* `Expose`: le widget est affiché ou réaffiché
* `FocusIn`: le widget reçoit le focus
* `FocusOut`: le widget pert le focus
## Dialogues
On peut ouvrir des fenêtres pour dire ou demander des choses.
### Fichiers
Demander où enregistrer un fichier, quel fichier ouvrir, choisir un dossier.
```python
from tkinter import filedialog
filetypes = [
("Texte", "*.txt"),
("Image PNG", "*.png"),
("Autre", "*.*")
]
chemin = tk.filedialog.asksaveasfilename(filetypes=filetypes)
print(chemin)
```
On peut remplacer `asksaveasfilename` par `askopenfilename` ou `askdirectory`.
### Couleur
Demander de choisir une couleur.
```python
from tkinter import colorchooser
color = colorchooser.askcolor(initialcolor='black')
print(color)
```
On peut aussi indiquer la couleur initiale avec sa notation hexadécimale `"#000000"`.

BIN
tutorial.pdf Normal file

Binary file not shown.