0% found this document useful (0 votes)
5 views19 pages

Créer des graphiques scientifiques avec Tkinter

This document describes the use of Tkinter, a Python library for creating graphical user interfaces. It presents the various available widgets (buttons, labels, entries, etc.), their functionality, and code examples for using them.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

Créer des graphiques scientifiques avec Tkinter

This document describes the use of Tkinter, a Python library for creating graphical user interfaces. It presents the various available widgets (buttons, labels, entries, etc.), their functionality, and code examples for using them.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

 (/)

(./page-python-beginner-course-documentation)
(./advanced-python-course-documentation-
French
ieoo-c
rdja
tcu
usdl-g-ounmentation-
t-rg(./
espa
fra
se
caIn)
-ac
tta
eb
uhe
dert-rea-rpepgay-p
drrnpb-e(./api
python

Install Tkinter
Tkinter is installed by default, if not, run the following command:

sudo apt-get install python-tk

In Python 3:

sudo apt-get install python3-tk

Python 2, Python 3
The modules are not the same depending on your version of Python. If the following message appears
during the execution of your script:

ImportError: No module named 'Tkinter'

The called module is not the right one for your python version.

Python 2 Python 3
Tkinter → tkinter
Tix → [Link]
ttk → [Link]
tkMessageBox → [Link]
tkColorChooser→ [Link]
tkFileDialog→ [Link] dialog
tkCommonDialog→ [Link]
tkSimpleDialog→ [Link]
tkFont → [Link]
Tkdnd → [Link]
ScrolledText → [Link]

Hello world
Here is the code for your first hello world

# coding: utf-8

from tkinter import *

window = Tk()

Hello World
[Link]()

[Link]()

A window like this should appear:

The Tkinter widgets


To create a graphical software, you need to add graphical elements into a window that
it is called a widget. This widget can be either a dropdown list or text.

The buttons
The buttons allow for an action to be offered to the user. In the example below, he is
propose to close the window.

exit button
Button(window, text='Close', command=[Link])
[Link]()

The labels
Labels are spaces intended for writing text. Labels are often used to describe a
widget like an input

# label
Label(fenetre, text='Default text', bg='yellow')
[Link]()

Entry / input
entry
StringVar()
set value to "default text"
Entry(fenetre, textvariable=string, width=30)
[Link]()

Checkbox
Checkboxes allow the user to check an option.

check button
button = Checkbutton(window, text="New?")
[Link]()

Radio buttons
Radio buttons are checkboxes that are in a group and in this group only one
element can be selected.

radiobutton
StringVar()
Radiobutton(window, text="Yes", variable=value, value=1)
bouton2 = Radiobutton(fenetre, text="Non", variable=value, value=2)
Radiobutton(window, text="Maybe", variable=value, value=3)
[Link]()
[Link]()
[Link]()

The lists
Lists allow retrieving a value selected by the user.
list
list = Listbox(window)
[Link](1, "Python")
[Link](2, "PHP")
[Link](3, "jQuery")
[Link](4, "CSS")
[Link](5, "Javascript")

[Link]()

Canvas
A canvas (canvas, painting in French) is a space in which you can draw or write.
what do you want:

canvas
Canvas(fenetre, width=150, height=120, background='yellow')
line1 = canvas.create_line(75, 0, 75, 120)
line2 = canvas.create_line(0, 60, 150, 60)
canvas.create_text(75, 60, text="Target", font="Arial 16 italic", fill="blue")
[Link]()

You can create other items:

create_arc() arc of circle


create_bitmap() bitmap
create_image() image
create_line() line
create_oval() oval
create_polygon() : polygon
create_rectangle() : rectangle
create_text() text
create_window() window

If you want to change the coordinates of an element created in the canvas, you can use the
methodcoords.

[Link](element, x0, y0, x1, y1)

To delete an element you can use the method delete

[Link](element)

You can find other useful methods by executing the following command:

printdir(Canvas())
You visit the following page infohost ([Link]
[Link]

Scale
The scale widget allows you to retrieve a numeric value via a scroll.

DoubleVar()
Scale(window, variable=value)
[Link]()

Frames
Frames are containers that allow for the separation of elements.

white

# frame 1
Frame1 = Frame(window, borderwidth=2, relief=GROOVE)
[Link](side=LEFT, padx=30, pady=30)

frame 2
Frame2 = Frame(window, borderwidth=2, relief=GROOVE)
[Link](side=LEFT, padx=10, pady=10)

frame 3 in frame 2
Frame3 = Frame(Frame2, bg="white", borderwidth=2, relief=GROOVE)
[Link](side=RIGHT, padx=5, pady=5)

Adding labels
Label(Frame1, text="Frame 1").pack(padx=10, pady=10)
Label(Frame2, text="Frame 2").pack(padx=10, pady=10)
Label(Frame3, text="Frame 3",bg="white").pack(padx=10, pady=10)

PanedWindow
Lepanedwindow is a container that can hold as many panels as needed arranged.
horizontally or vertically.
p = PanedWindow(window, orient=HORIZONTAL)
[Link](side=TOP, expand=Y, fill=BOTH, pady=2, padx=2)
Panel 1
Panel 2
Panel 3
[Link]()

Spinbox
Laspinbox offers the user to choose a number.

s = Spinbox(window, from_=0, to=10)


[Link]()

LabelFrame
The labelframe is a frame with a label.

l = LabelFrame(window, text="Frame Title", padx=20, pady=20)


[Link](fill="both", expand="yes")

Label(l, text="Inside the frame").pack()

The alerts
To be able to use the alerts of your OS, you can import the moduletkMessageBox(Python
2).

from tkMessageBox import*

For python 3:
from [Link] import *

Usage example:

defcallback():
Title 1
Title 2
else:
Title 3
Title 4

Action

Here are the possible alerts:

showinfo()
show warning()
showerror()
askquestion()
askokcancel()
askyesno()
askretrycancel()

Menu bar
It is possible to create a menu bar like this:
defalert():
Alert: Bravo!

menubar = Menu(window)

menu1 = Menu(menubar, tearoff=0)


menu1.add_command(label="Créer", command=alert)
menu1.add_command(label="Edit", command=alert)
menu1.add_separator()
menu1.add_command(label="Quitter", command=[Link])
menubar.add_cascade(label='File', menu=menu1)

menu2 = Menu(menubar, tearoff=0)


Cut
Copy
menu2.add_command(label="Paste", command=alert)
menubar.add_cascade(label="Edit", menu=menu2)

menu3 = Menu(menubar, tearoff=0)


menu3.add_command(label="A propos", command=alert)
menubar.add_cascade(label="Help", menu=menu3)

[Link](menu=menubar)

Know all the methods/options of a widget


To do this, simply execute the following line:

print dir(Button())

Standard attributes
It is possible to change the value of attributes present on the widgets.

Place widgets
It is possible to place the widgets using the parameter side:

side=TOP high
left
side=BOTTOM : base
right
Example:

Canvas(window, width=250, height=100, bg='ivory').pack(side=TOP, padx=5, pady=5)


Button(window, text='Button 1').pack(side=LEFT, padx=5, pady=5)
Button(window, text='Button 2').pack(side=RIGHT, padx=5, pady=5)

Another example:

Canvas(window, width=250, height=50, bg='ivory').pack(side=LEFT, padx=5, pady=5)


Button(window, text='Button 1').pack(side=TOP, padx=5, pady=5)
Button(window, text='Button 2').pack(side=BOTTOM, padx=5, pady=5)

Units of measurement
If you specify a dimension using an integer, the unit used will be 'pixels'. However, it is...
possible to change the unit:

inches
mm : millimeter
c : centimeter

Dimension options
height Height of the widget.
width Widget width.
padx, pady Additional space around the widget. X for horizontal and V for vertical.
border width Border size.
Width of the rectangle when the widget has focus.
selectborderwidth: Width of the three-dimensional border around the selected widget.
wrap length Maximum number of lines for widgets in 'word wrapping' mode.

Color options
It is possible to indicate a color value by its name in English: "white", "black", "red",
"yellow", etc. or by its hexadecimal code: #000000, #00FFFF, etc.
background (or bg) background color of the widget.
foreground (or fg) foreground color of the widget.
active background background color of the widget when it is active.
activeForeground foreground color of the widget when the widget is active.
foreground color of the widget when the widget is disabled.
Background color of the highlight region when the widget has focus.
highlight color foreground color of the highlighted area when the widget is focused
select background Background color for selected items.
selectforeground foreground color for selected elements.

The cursor
You can change the appearance of your cursor:

Button(window, text='arrow', relief=RAISED, cursor='arrow').pack()


Button(window, text='circle', relief=RAISED, cursor='circle').pack()
Button(window, text='clock', relief=RAISED, cursor='clock').pack()
Button(window, text="cross", relief=RAISED, cursor="cross").pack()
Button(window, text='dotbox', relief=RAISED, cursor='dotbox').pack()
Button(window, text='exchange', relief=RAISED, cursor='exchange').pack()
Button(window, text="flower", relief=RAISED, cursor="flower").pack()
Button(window, text="heart", relief=RAISED, cursor="heart").pack()
Button(window, text='man', relief=RAISED, cursor='man').pack()
Button(window, text="mouse", relief=RAISED, cursor="mouse").pack()
Button(window, text='pirate', relief=RAISED, cursor='pirate').pack()
Button(window, text="plus", relief=RAISED, cursor="plus").pack()
Button(window, text="shuttle", relief=RAISED, cursor="shuttle").pack()
Button(window, text='sizing', relief=RAISED, cursor='sizing').pack()
Button(window, text='spider', relief=RAISED, cursor='spider').pack()
Button(window, text='spraycan', relief=RAISED, cursor='spraycan').pack()
Button(window, text='star', relief=RAISED, cursor='star').pack()
Button(window, text='target', relief=RAISED, cursor='target').pack()
Button(window, text='tcross', relief=RAISED, cursor='tcross').pack()
Button(window, text='trek', relief=RAISED, cursor='trek').pack()
Button(window, text='watch', relief=RAISED, cursor='watch').pack()

The relief
You can change the relief on your elements:

FLAT
RAISED
SUNken
GROOVE
RIDGE

b1 = Button(window, text='FLAT', relief=FLAT).pack()


Button(window, text='RAISED', relief=RAISED).pack()
b3 = Button(window, text='SUNKEN', relief=SUNKEN).pack()
b4 = Button(window, text ='GROOVE', relief=GROOVE).pack()
b5 = Button(window, text ='RIDGE', relief=RIDGE).pack()
The grid
It is possible to place the elements by reasoning in a grid:

for line in range(5):


for column in range(5):
Button(window, text='L%s-C%s' % (line, column), borderwidth=1).grid(row=line, column=col)

Button(window, text='L1-C1', borderwidth=1).grid(row=1, column=1)


Button(window, text='L1-C2', borderwidth=1).grid(row=1, column=2)
Button(window, text='L2-C3', borderwidth=1).grid(row=2, column=3)
Button(window, text='L2-C4', borderwidth=1).grid(row=2, column=4)
Button(window, text='L3-C3', borderwidth=1).grid(row=3, column=3)

Insert an image
To integrate an image, you can create a canvas and add it inside like this:

PhotoImage(file="my_photo.png")

canvas = Canvas(window, width=350, height=200)


canvas.create_image(0, 0, anchor=NW, image=photo)
[Link]()
Retrieve the value of an input
To retrieve the value of an input, you will need to use the method get():

defrecupere():
showinfo("Alert", [Link]())

StringVar()
[Link]("Value")
entry = Entry(window, textvariable=value, width=30)
[Link]()

bouton = Button(fenetre, text="Valider", command=recupere)


[Link]()

Retrieve an image and display it


To do this, you need to import the following module:

from [Link] import*

openfilename(title="Open an image", filetypes=[('png files', '.png'), ('all files', '.*')])


PhotoImage(file=filepath)
canvas = Canvas(window, width=[Link](), height=[Link](), bg="yellow")
canvas.create_image(0, 0, anchor=NW, image=photo)
[Link]()

The function askopenfilename returns the path of the file you selected with the name of
this one.

/home/olivier/my_photo.png
Retrieve a text file and display it
Open your document
file = open(filename, "r")
content = [Link]()
[Link]()

Label(window, text=content).pack(padx=10, pady=10)

The events
You can retrieve user actions through events.

For each widget, you can bind an event, for example to say when
the user presses such a key, do this.

Here is an example that captures the keys pressed by the user:

def keyboard(event):
touch = [Link]
print(touch)

Canvas(window, width=500, height=500)


canvas.focus_set()
[Link]("<Key>", keyboard)
[Link]()

It is noted that the event is framed by chevrons.

Other events exist:

<Button-1> Left click


<Button-2> Click medium
<Button-3> Right click
Double-Click Right
Double left click
<KeyPress> Pressing a key
KeyPress-a Pressing the key A (lowercase)
<KeyPress-A> Press the Shift key
Return Pressing the enter key
<Escape> Touch Escape
Up Pressing the up directional arrow
Down Press down on the downward directional arrow
<ButtonRelease> When you release the click
Motion Mouse movement
<B1-Motion> Mouse movement with left click
Cursor entry into a widget
Leave Cursor exit in a widget
Configure Window resizing
<Map> <Unmap> Opening and iconification of the window
Mouse Wheel Use of the roulette

To remove the event binding, you can use the methods unbind or unbind_all.

Here is an example where you can move a square with the arrow keys:
function called when the user presses a key
def keyboard(event):
globalcoords

[Link]

iftouche == "Up":
(coords[0], coords[1] - 10)
Down
coords = (coords[0], coords[1] + 10)
Right
coords = (coords[0] + 10, coords[1])
Left
coords = (coords[0] -10, coords[1])
change of coordinates for the rectangle
[Link](rectangle, coords[0], coords[1], coords[0]+25, coords[1]+25)

canvas creation
Canvas(window, width=250, height=250, bg='ivory')
initial coordinates
coords = (0, 0)
creation of the rectangle
canvas.create_rectangle(0,0,25,25,fill="violet")
adding the bond on the keyboard keys
canvas.focus_set()
[Link]("<Key>", keyboard)
canvas creation
[Link]()

Reading advice for tkinter:

[Link]
([Link] - [Link]
([Link] - develop
[Link] - sebsauvage
([Link]

Python & Django Books: Reading Recommendations

ie=UTF8&camp=1642&creative=6746&creativeASIN=2746071711&linkCode=as2&tag=pythondjango-
21&linkId=bdf2387af4f5ebddbf6a49ab0369c185)
([Link]

ie=UTF8&camp=1642&creative=6746&creativeASIN=1797866478&linkCode=as2&tag=pythondjango-
21&linkId=1bbb923046b465218bd107d69482d5)

([Link]

ie=UTF8&camp=1642&creative=6746&creativeASIN=2409012264&linkCode=as2&tag=pythondjango-
21&linkId=635e1fd05fa3fa8a13d66632af388dd8)

File and folder management (./page-file-and-folder-management-python)


Scientific graphs  (./create-scientific-graphs-python-learn)

(./course-page- (./course-page- (./page-django- (./page-raspberry-

python-beginner- python-advance- course-tutorials- pi-learn-beginner


documentation documentation documentation buy-python)
French French

Python beginner

Python Presentation (./)

Install Python (./page-learn-install-python-computer)

Python interpreter (./using-python-interpreter)

Python IDE Editors (./page-python-editors-free-paid-ide)

Calculations and variables (./page-learn-beginner-python-variables)


The lists (./page-learn-lists-list-tables-arrays-list-array-python-
beginner-course

Tuples (./page-learn-tuples-tuple-python)

Dictionaries (./page-learn-dictionary-python)

Functions (./page-learn-create-function-in-python)

Native functions (./page-builtin-built-in-internal-functions-python)

Conditions if elif else (./page-learn-conditions-if-conditional-structures-


else-python-beginner-course

For / While Loop (./page-learn-python-loops)

The modules/packages (./page-python-modules-package-module-course-


computer-programming-beginners

Exceptions (./page-learn-exceptions-except-python-beginner-course)

List comprehensions (./page-comprehension-list-lists-python-course-


beginners)

Object-oriented programming (./page-learn-object-oriented-programming-


object-poo-classes-python-beginners-course

Decorators (./page-decorateurs-decorator-python-cours-debutants)

Iterators/Generators
python)

Regular expressions (./page-regular-expressions-regular-python)

Read / Edit a file (./page-read-write-create-file-python)

PEP 8 / best practices (./page-pep-8-best-practices-code-python-


to learn

Black code formatter (./page-black-code-formatter)

Advanced Python

Differences python 2 / 3 (./page-syntax-differences-python2-python3-


differences)

Python encoding (./page-python-encoding-encode-decode-unicode-ascii-codec-


character-accents-problems-string-utf8

Pip installs your libraries (./page-pip-installer-libraries-automatically)

Virtualenv (./page-virtualenv-python-virtual-environment)
Debug (./debugger-debug-python-ipython-pdb-pdbpp-course-
tutorial-script

Python Path (./page-python-path-pythonpath)

File and folder management (./page-file-folder-management-python)

Graphical interface tKinter (./page-tkinter-graphical-interface-python-tutorial)

Scientific graphs (./page-create-scientific-graphs-python-


to learn

Asynchronous programming (./page-asynchronous-programming-python-thread-


threading

XML and Python (./page-xml-python-xpath)

BeautifulSoup / HTML parser (./page-beautifulsoup-html-parser-python-library-


xml)

Create an executable (./page-cx_freeze-create-executables-python-course-


to learn

Shared folder / samba (./page-shared-folder-samba-network-python-fstab)

FTP (./page-python-ftp-create-copy-view-folder-files)

Fabric SSH (./page-python-ssh-connect-host-distant-sftp-os-fabric-client)

Send an SMTP email (./page-python-send-smtp-email)

Network / socket (./network-sockets-python-port)

Database (./page-database-data-base-data-query-sql-mysql-postgre-
sqlite

Create a web server (./page-python-serveur-web-creer-rapidement)

Websocket & Crossbar (./page-websocket-python-crossbar-push-socket-publish-


subscribe-call-remote-register-wamp

Static site generator (./page-static-site-generator-python-django)

Django

Django Presentation (./page-django-introduction-python)

Install Django (./page-django-installer-python)

Initialize a Django project (./page-django-initialize-create-python)

Create a Django application (./page-django-application-create-python)


Django ORM (./page-django-orm-learn-database-database-queryset-
models)

Login Django (./page-django-login-basic-authentication-learn-create-


course-tutorial-python

The fields of the models (./page-django-model-fields-orm-model)

Django admin interface (./page-django-interface-admin-administration-settings-


django-contrib-auth

Queryset (./page-django-query-set-queryset-manager)

Many to many relation


relationships-orm

The views (./page-django-vues-views-generic-generiques-python)

The forms (./page-django-forms-fields)

CSRF Token (./page-django-csrf-token-security-forms-python-ajax-post-


jquery-angularjs

The middlewares (./page-django-middlewares-views-views-request-response-


process-before-after

Django Templates (./page-django-templates-structure-template-HTML-variables-


loops-tags-more-page-dry-application-project-modify-folder

Context Processor (./page-django-context-processor-template)

Django Signals
tutorial-example

Xadmin (./page-django-xadmin-bootstrap-twitter-theme-export-xls-csv-xml-
python-web-plugin

Django select2 (./page-django-admin-select2-admin-ajax-many-to-many-foreign-


key-form-widget-django_select2

Crispy Forms (./page-django-crispy-form-bootstrap-twitter-html)


eldset-inline-dynamic-template

AngularJS and Django (./page-django-angularjs-angular-js-coffee-script-


coffeescript-python-course-tutorial-examples

Upload a file in ajax (./page-django-comment-uploader-file-image-


course-learn-python-upload-
Django Rest Framework (./page-django-rest-framework-drf-course-tutorial-tutorial-
examples)

Django deployment (./page-django-deployment-python-production-


linux-gunicorn-supervisor-nginx-installer-configurer-http-web-server

Raspberry Pi

Presentation Raspberry Pi (./page-raspberry-pi-presentation-python-what-is-it-


learn-nano-computer-video

Install Raspbian (./page-raspberry-pi-install-installer-debian-linux-windows-


ubuntu

Static IP (./page-raspberry-pi-static-ip-address)

Samba / share a folder


samba-debian

Play video 1080p (./page-raspberry-pi-reading-play-video-1080p-full-hd-omxplayer-


command-line

Install VPN (./page-raspberry-pi-installer-vpn-dns-openvpn-debian-python)

Client torrent (./page-raspberry-pi-installer-client-torrent-transmission-


download-dl-python

Site

Contact the author (./page-contact)

Legal notices (./page-mentions-legales)

Learn programming course Python 3


Django internet web - Beginner and expert documentation
English version (/en/)

You might also like