1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
| #!/usr/bin/env python
# -*- coding:UTF-8 -*-
#-------------------------------------------------------------------------------
# Name: Combobox
# Purpose:
#
# Author: MzBouba
#
# Created: 13/04/2012
# Copyright: (c) MACHADO.F 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
"""
Options standard
activestyle :Spécifie l'apparence de la ligne active de la liste.
background / bg :Couleur de fond.
disabledbackground :Couleur de fond quand le widget est à l'état DISABLED.
disabledforeground :Couleur de premier plan affichée quand l'état
du widget est DISABLED.
exportselection :Par défaut, l'utilisateur sélectionner le texte avec
la souris et le texte choisi sera exporté au
presse-papiers.
Pour mettre hors service ce comportement,
utilisez exportselection=0.
command :Lance une commande lors du changement de la valeur du
champ de saisie.
borderwidth / bd :Largeur de la frontière autour de la combobox.
cursor :Curseur utilisé quand la souris est sur le widget.
foreground / fg :Couleur du texte.
highlightbackground :Couleur highlight quand le widget n'a pas de focus.
highlightcolor :Couleur highlight quand le widget a un focus.
highlightthickness :Intensité de la couleur de focus.
height :Nombre de lignes affichés dans la liste.
insertbackground :Couleur du curseur d'insertion.
insertborderwidth :
insertofftime :Clignotement du curseur, temps où il est éteint.
insertontime :Clignotement du curseur, temps où il est allumé.
insertwidth :Largeur du curseur. 2 pixels par défaut.
items :Liste d'éléments.
justify :Emplacement du texte.
listvariable :StringVar connecté à la liste complète.
matchrequired :La valeur de saisie doit être dans la liste.
Si elle n'y figure pas, le premier élément de la liste
est sélectionné
nodouble :Enlève les doubles de la liste.
0:Ne fait rien (par défaut)
1:Supprime les doubles
readonlybackground :Couleur de fond l'état du widget est "readonly".
relief :Effets tridimensionnels autour de l'entrée de texte.
selectbackground :Couleur de fond à l'affichage du texte sélectionné.
selectborderwidth :Largeur de la frontière utilisé autour du texte
sélectionné. Par défaut un pixel.
selectforeground :Couleur de premier plan du texte sélectionné.
sort :Tri la liste suivant la valeur renseignée.
None :Pas de tri (par défaut)
sort :Tri croissant par ordre alphanumérique
reversed :Tri décroissant par ordre alphanumérique
reverse :inversion de la liste
state :Etat du widget (NORMAL, DISABLED).
takefocus :Normalement, le focus contrôle le widget;
fournissez la valeur 0 à cette option pour obtenir
l'interruption du contrôle de focus.
textvariable :StringVar associé à la zone de saisie.
width :Largeur de l'étiquette en caractères (pas pixels!).
La largeur est basée sur la moyenne des caractères,
donc quelques chaînes dans des polices de caractères.
proportionnelles ne peuvent pas aller à cette longueur.
xscrollcommand :A lier avec une scrollbar pour faire défiler le texte
de la boite de saisie si ce texte est trop long.
Methode
append :Ajout d'un élément à la fin d'une liste.*
configure_ :Permet de modifier les options standards de la Combobox.
config_ :cf. configure_
clear_list :Vide la liste
extend :Concatène la liste d'origine avec la liste <otherlist>.*
get :Récupère la valeur du champ de saisie.
index_to_item :Renvoi l'élément de la liste se trouvant à la ligne(index)
insert_ :Ajout d'un élément dans la liste à la ligne index.*
item_to_index :Renvoi l'<index> (ligne), de la liste, correspondant
à <item>
remove :Supprime un élément de la liste
set :Modifie le champ de saisie avec la valeur renseignée.
size :Renvoi le nombre d'élément de la liste
* Les méthodes de suppression de double et de tri sont aussi appelé.
Vérifier les options nodouble et sort.
"""
try:
from tkinter import *
except:
from Tkinter import *
from sys import platform
#from time import *
#import tkinter.messagebox as tkMessageBox
class Combobox(Frame):
"""Champ de saisie associé à une liste déroulante"""
def __init__(self, master=None, _class='Combobox', **Arg):
#command='', items=[], matchrequired=0, nodouble=0, sort=None
"""Construit un Widget Combobox avec master comme parent
Option Standard
activestyle, background / bg,
disabledbackground, disabledforeground,
exportselection, borderwidth / bd, command,
cursor, foreground / fg, highlightbackground,
highlightcolor, highlightthickness, height,
insertbackground, insertborderwidth,
insertofftime, insertontime, insertwidth,
items, justify, listvariable, matchrequired,
nodouble, readonlybackground, relief,
selectbackground, selectborderwidth,
selectforeground, sort, state, takefocus,
textvariable, width, xscrollcommand
Methode
append, configure_, config_, extend,
get, index_to_item, insert_, item_to_index,
remove, set, size
"""
self.index = -1
self.sVar = StringVar()
self.widget_option = {}
self.widget_option['Button'] = {
'bg': 'SystemButtonFace',
'background': 'SystemButtonFace',
'cursor': '',
'fg': 'SystemButtonText',
'foreground': 'SystemButtonText',
'highlightbackground': 'SystemButtonFace',
'highlightcolor': 'SystemWindowFrame',
'highlightthickness': 1,
'relief': 'raised',}
self.widget_option['Entry'] = {
'bg': 'SystemWindow',
'background': 'SystemWindow',
'cursor': 'xterm',
'disabledbackground': 'SystemButtonFace',
'disabledforeground': 'SystemDisabledText',
'exportselection': 1,
'fg': 'SystemWindowText',
'foreground': 'SystemWindowText',
'highlightbackground': 'SystemButtonFace',
'highlightcolor': 'SystemWindowFrame',
'highlightthickness': 0,
'insertbackground': 'SystemWindowText',
'insertborderwidth': 0,
'insertofftime': 300,
'insertontime': 600,
'insertwidth': 2,
'justify': 'left',
'readonlybackground': 'SystemButtonFace',
'relief': 'sunken',
'selectbackground': 'SystemHighlight',
'selectborderwidth': 0,
'selectforeground': 'SystemHighlightText',
'state': 'normal',
'takefocus': '',
'textvariable': '',
'width': 20,
'xscrollcommand': '',}
self.widget_option['Frame'] = {
'bd': 0,
'borderwidth': 0,
'cursor': '',
'height': 0,
'highlightbackground': 'SystemButtonFace',
'highlightcolor': 'SystemWindowFrame',
'highlightthickness': 0,
'padx': 0,
'pady': 0,
'relief': 'flat',
'takefocus': '0',
'width': 0,}
self.widget_option['Listbox'] = {
'activestyle': 'underline',
'bg': 'SystemWindow',
'background': 'SystemWindow',
'cursor': '',
'exportselection': 1,
'fg': 'SystemButtonText',
'foreground': 'SystemButtonText',
'height': 10,
'highlightbackground': 'SystemButtonFace',
'highlightcolor': 'SystemWindowFrame',
'highlightthickness': 1,
'listvariable': '',
'relief': 'sunken',
'selectbackground': 'SystemHighlight',
'selectborderwidth': 0,
'selectforeground': 'SystemHighlightText',
'width': 20,}
self.widget_option['Scrollbar'] = {
'bg': 'SystemButtonFace',
'background': 'SystemButtonFace',
'cursor': '',
'highlightbackground': 'SystemButtonFace',
'highlightcolor': 'SystemWindowFrame',
'highlightthickness': '0',
'relief': 'sunken',}
self.widget_option['Toplevel'] = {
'bg': 'SystemButtonFace',
'background': 'SystemButtonFace',
'cursor': '',
'highlightbackground': 'SystemButtonFace',
'highlightcolor': 'SystemWindowFrame',
'highlightthickness': 0,
'relief': 'flat',}
self.widget_option['Combobox'] = {
'activestyle': 'underline',
'background': 'SystemButtonFace',
'borderwidth': 0,
'command': '',
'cursor': '',
'disabledbackground': 'SystemButtonFace',
'exportselection': 1,
'foreground': 'SystemWindowText',
'height': 10,
'highlightbackground': 'SystemButtonFace',
'highlightcolor': 'SystemWindowFrame',
'highlightthickness': 10,
'insertbackground': 'SystemWindowText',
'insertofftime': 300,
'insertontime': 600,
'insertwidth': 2,
'items': [],
'justify': 'left',
'listvariable': '',
'matchrequired': 0,
'nodouble': 0,
'readonlybackground': 'SystemButtonFace',
'relief': 'raised',
'selectbackground': 'SystemHighlight',
'selectborderwidth': 0,
'sort': None,
'state': 'normal',
'takefocus': 0,
'textvariable': '',
'width': 20,
'xscrollcommand': '', }
self.__update_arg__(**Arg)
# <Frame>---------------------------------------------------------------
Frame.__init__(self, master, self.widget_option['Frame'])
self.bind('<FocusOut>', self.__match_required__)
self.__initialize__()
# Initialise la partie graphique
def __initialize__(self):
"""Fonction interne"""
# Autocomplétion lors de la saisie de texte
def __auto_completion__(event):
"""Fonction interne"""
if event.keysym not in ['BackSpace', 'Delete', 'Down', 'Up']:
index = -1
for item in self.widget_option['Combobox']['items']:
index += 1
if self.sVar.get() in item[:(len(self.sVar.get()))]:
self.sVar.set(item)
self.entry.select_range(INSERT, END)
self.index = index
self.invoke()
break
else:
self.invoke()
# Actualisation de l'index
def _update_index(delta):
"""Function interne"""
if self.widget_option['Combobox']['items']:
self.index = (self.index + delta) % len(self.widget_option['Combobox']['items'])
self.entry.delete(0, END)
self.sVar.set(self.widget_option['Combobox']['items'][self.index])
self.invoke()
else:
self.index = -1
# <Entry>---------------------------------------------------------------
self.entry = Entry(self, self.widget_option['Entry'],
borderwidth=0, font='Arial, 8',
textvariable=self.sVar)
self.entry.grid(row=0, column=0)
# <Button>--------------------------------------------------------------
self.button = Button(self, self.widget_option['Button'],
disabledforeground='black',
borderwidth=0, command=self.__create_toplevel__,
font='Arial, 7', height=1, takefocus=0,
text='▼')
self.button.grid(row=0, column=1)
self.entry.bind('<Down>', lambda e: _update_index(1)) # touche bas
self.entry.bind('<Up>', lambda e: _update_index(-1)) # touche haut
if platform.startswith('linux'):
self.entry.bind('<Button-4>', lambda e: _update_index(-1))
self.entry.bind('<Button-5>', lambda e: _update_index(1))
elif platform == 'win32':
self.entry.bind('<MouseWheel>', lambda e: _update_index(int(-e.delta/120)))
self.button.config(background='white')
elif platform == 'darwin':
self.entry.bind('<MouseWheel>', lambda e: _update_index(int(-e.delta)))
self.entry.bind('<KeyRelease>', __auto_completion__)
# Créer la <Toplevel> contenant la <Listbox>
def __create_toplevel__(self):
"""Fonction interne"""
# Rend l'utilisation du <bouton-1> au <Button>
def active_button(event=None):
self.button['state']=NORMAL
# Ferme la liste
def close_list(event=None):
"""Fonction interne"""
self.toplevel.destroy()
self.after(1, active_button)
# Déplacement de la souris dans <Listbox>
def move_mouse(event):
"""Fonction interne"""
self.listbox.selection_clear(0, END)
self.listbox.activate(self.listbox.nearest(event.y))
self.listbox.selection_set(self.listbox.nearest(event.y))
# Sélection d'une item dans <Listbox>
def select_item(event=None):
"""Fonction interne"""
if int(self.listbox.size()): # <Listbox> non vide
index = self.listbox.curselection() # renvoie un tuple d'index
ind0 = int(index[0]) # on ne garde que le premier
self.index = ind0
item = self.listbox.get(ind0)
# <Entry>: Actualisation suivant l'item choisi dans la <Listbox>
self.sVar.set(item)
# <Entry>: Prend le focus
self.entry.focus_set()
# <Entry>: Déplace le curseur au début
self.entry.icursor(0)
# <Entry>: Sélectionne le mot
self.entry.select_range(0, END)
# <Toplevel>: Destruction
close_list()
self.invoke()
# <Toplevel>------------------------------------------------------------
self.toplevel=Toplevel(self, self.widget_option['Toplevel'])
# <Toplevel> retrait du contour
self.toplevel.overrideredirect(1)
# <Toplevel> tjs en 1er plan
self.toplevel.transient()
# <Toplevel>: Perte du focus, deplacement de la fenetre, la <Toplevel> se ferme
if platform.startswith('linux'):
self.toplevel.bind('<Leave>', close_list)
self.bind('<Unmap>', close_list)
self.bind('<Configure>', close_list)
self.toplevel.bind('<FocusOut>', close_list)
self.button['state']=DISABLED
# <Listbox>-------------------------------------------------------------
self.listbox = Listbox(self.toplevel, self.widget_option['Listbox'])
self.listbox.pack(side=LEFT, fill=BOTH, expand=1)
# <ListBox>: Remplissage
for it in self.widget_option['Combobox']['items']:
self.listbox.insert(END, it)
# <Listbox>: prend le focus
self.listbox.focus()
# <Listbox>: Action
self.listbox.bind('<Button-1>', select_item)
self.listbox.bind('<Motion>', move_mouse)
# <listbox>: Sélection de l'item = <Entry>
if self.sVar.get() in self.widget_option['Combobox']['items']:
index = self.item_to_index(self.sVar.get())
if self.index != -1:
if self.index_to_item(self.index) == self.sVar.get():
if self.index != index:
index = self.index
else:
index = 0
# <listbox>: Positionne le cuseur sur la valeur de <Entry>
self.listbox.activate(index)
self.listbox.selection_set(index)
self.listbox.see(index)
# <Scrollbar>-----------------------------------------------------------
if len(self.widget_option['Combobox']['items']) > self.widget_option['Combobox']['height']:
# <Scrollbar>: Association avec <Listbox>
self.scrollbar = Scrollbar(self.toplevel,
self.widget_option['Scrollbar'],
borderwidth=0,
command=self.listbox.yview, width=15)
# <scrollbar>: Implantation
self.scrollbar.pack(expand=YES, fill=Y)
# <Listbox>: Association avec <scrollbar>
self.listbox.config(yscrollcommand=self.scrollbar.set)
#<Toplevel>: Geometrie#<Toplevel>: Geometrie
self.toplevel.geometry("%dx%d+%d+%d" % (self.winfo_reqwidth(),
self.listbox.winfo_reqheight(),
self.winfo_rootx(),
self.winfo_rooty()+self.winfo_reqheight()))
# Vérifie que la valeur saisie est dans la liste
def __match_required__(self, event=None):
"""Fonction interne"""
if self.widget_option['Combobox']['matchrequired']:
if self.widget_option['Combobox']['items']:
try:
# Si la <Listbox> prend le focus, on ne vérifie pas
if self.nametowidget(self.focus_get()) == self.nametowidget(self.listbox):
listboxId = 1
except:
listboxId = 0
if not listboxId:
if not self.sVar.get() in self.widget_option['Combobox']['items']:
if self.index == -1:
self.sVar.set(self.widget_option['Combobox']['items'][0])
self.index = 0
self.sVar.set(self.widget_option['Combobox']['items'][self.index])
# Suppression des doubles dans la liste
def __nodouble_in_list__(self):
"""Fonction interne"""
if self.widget_option['Combobox']['nodouble']:
self.widget_option['Combobox']['items']=list(set(self.widget_option['Combobox']['items']))
# Tri la liste suivant l'option
def __sort_list__(self):
"""Fonction interne"""
if self.widget_option['Combobox']['sort'] == 'sort':
self.widget_option['Combobox']['items'].sort()
elif self.widget_option['Combobox']['sort'] == 'reversed':
self.widget_option['Combobox']['items'].sort(reverse=True)
elif self.widget_option['Combobox']['sort'] == 'reverse':
self.widget_option['Combobox']['items'].reverse()
# Actualise le dictionnaire des options des widgets
def __update_arg__(self, **Arg):
"""Fonction interne"""
for k in Arg:
for widget in self.widget_option:
if k in self.widget_option[widget]:
self.widget_option[widget][k]=Arg[k]
if not isinstance(self.widget_option['Combobox']['items'], list):
if isinstance(self.widget_option['Combobox']['items'], tuple):
self.widget_option['Combobox']['items'] = list(self.widget_option['Combobox']['items'])
else:
self.widget_option['Combobox']['items'] = ['Liste incorrecte']
self.__nodouble_in_list__()
self.__sort_list__()
#
def append(self, string):
"""Ajout d'un élément à la fin d'une liste.
Les méthodes de suppression de double et de tri sont
aussi appelé.
Vérifier les options nodouble et sort."""
self.widget_option['Combobox']['items'].append(string)
self.__nodouble_in_list__()
self.__sort_list__()
#
def configure_(self, **Arg):
"""Modifie l'option ou les options spécifié"""
self.__update_arg__(**Arg)
self.configure(self.widget_option['Frame'])
for widget in self.winfo_children():
widget.configure(self.widget_option[widget.winfo_class()])
def config_(self, **Arg):
"""Modifie l'option spécifié"""
return self.configure_(**Arg)
#
def extend(self, otherlist):
"""Concatène la liste d'origine avec la liste <otherlist>.
Les méthodes de suppression de double et de tri sont
aussi appelé.
Vérifier les options nodouble et sort."""
self.widget_option['Combobox']['items'].extend(otherlist)
self.__nodouble_in_list__()
self.__sort_list__()
#
def get(self):
"""Récupère la valeur du champ de saisie"""
return self.sVar.get()
#
def index_to_item(self, index):
"""Renvoi l'élément de la liste se trouvant à la ligne(index)"""
return self.widget_option['Combobox']['items'][index]
#
def insert_(self, string, index=END):
"""Ajout d'un élément dans la liste à la ligne index.
Les méthodes de suppression de double et de tri sont
aussi appelé.
Vérifier les options nodouble et sort."""
if index == END:
index = len(self.widget_option['Combobox']['items'])
self.widget_option['Combobox']['items'].insert(string, index)
self.__nodouble_in_list__
self.__sort_list__
#
def item_to_index(self, string):
"""Renvoi la ligne (index) dans la liste du premier élément
correspondant trouvé"""
return self.widget_option['Combobox']['items'].index(string)
# lance la commande associé à la combobox en récupérant le contenu de <Entry>
def invoke(self):
"""Fonction interne"""
if self.widget_option['Combobox']['command']:
self.widget_option['Combobox']['command'](self.sVar.get())
# Retourne le contenu de la liste
def list_(self):
"""Renvoi le contenu de la liste"""
return self.widget_option['Combobox']['items']
#
def remove(self, string):
"""Supprime un élément de la liste"""
self.widget_option['Combobox']['items'].remove(string)
#
def set(self, string):
"""Modifie le champ de saisie avec la valeur renseignée"""
self.sVar.set(string)
# <Entry>: Déplace le curseur au début
self.entry.icursor(0)
self.entry.selection_range(0, END)
#
def size(self):
"""Renvoi le nombre d'élément de la liste"""
return len(self.widget_option['Combobox']['items'])
def main():
mylist = ('Pommes', 'Poires', 'Abricot', 'Ananas', 'Raisin','Orange',
'Clémentine', 'Cerise', 'Mandarine', 'Peche', 'Poires', 'Abricot')
listempty = ['saucisse', 'merguez']
def label_value(string):
label.config({'text': string})
def click_button():
label.config(text='rien et autre, ajouté à la liste du bas')
combobox1.config_(items=['rien', 'autre', 'rien', 'autre', 'rien', 'autre', 'rien', 'autre'], width=5, cursor='boat')
window = Tk()
combobox = Combobox(window,
activestyle='dotbox',
borderwidth=2,
command=label_value,
insertborderwidth=10,
items= mylist,
relief=GROOVE,
height=10,
width=30,
nodouble = 1,
matchrequired=1,
sort='sort')
combobox1 = Combobox(window,
activestyle='dotbox',
borderwidth=2,
#items=listempty,
matchrequired=1,
nodouble = 1,
width=30)
button = Button(window, text='test', command=click_button)
label = Label(window, bg='white')
label.grid(row=0, column=0, padx=5, pady=5, sticky=EW)
button.grid(row=1, column=0, padx=5, pady=5)
combobox.grid(row=2, column=0, padx=5, pady=5)
combobox1.grid(row=3, column=0, padx=5, pady=5)
window.mainloop()
if __name__ == '__main__':
main() |