• Tkinter > les fenêtres

      BASE

      from tkinter import *
      w = Tk()
      ...code...
      w.mainloop()

      TITRE

      w.title('le titre')

      GÉOMÉTRIE DE LA FENÊTRE

      Position et dimensions

      w.geometry('largeurxhauteur+posH+posV')
      w.geometry('200x400+50+100')
      w.geometry("800x600")

      dimensions de l’écran

      w_window = w.winfo_screenwidth() # largeur de l'écran
      h_window = w.winfo.screenheight() # hauteur de l'écran

      plein écran

      w_window = window.winfo_screenwidth()
      h_window = window.winfo_screenheight()
      w.geometry("%dx%d+0+0" % (w_window, h_window))
      w.geometry("{}x{}+0+0".format(w_window, h_window))
      w.geometry(f"{w_window}x{h_window}+0+0") # depuis 3.6

      CENTRER la fenêtre au milieu de l’écran

      H_fen = 200
      L_fen = 200
      w.geometry("%dx%d%+d%+d" % (H_fen,L_fen,(w.winfo_screenwidth()-L_fen)//2,(w.winfo_screenheight()-H_fen)//2))

      Empêcher le redimensionnement de la fenêtre

      w.resizable(width=False, height=False)

      Maximiser la fenêtre

      En appuyant sur la touche ESC, la fenêtre reprendra la dimension 200×200+0+0 par défaut :

       

      import Tkinter as tk
      
      class FullScreenApp(object):
          def __init__(self, master, **kwargs):
              self.master=master
              pad=3
              self._geom='200x200+0+0'
              master.geometry("{0}x{1}+0+0".format(master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
              master.bind('<Escape>',self.toggle_geom)
          def toggle_geom(self,event):
              geom=self.master.winfo_geometry()
              print(geom,self._geom)
              self.master.geometry(self._geom)
              self._geom=geom
      
      root=tk.Tk()
      app=FullScreenApp(root)
      root.mainloop()

       

      note: avec root.overrideredirect(True) the <Escape> doesn’t call anything on my machine (Ubuntu). Without root.overrideredirect the title bar is shown.

      +0+0 part in self._geom and method `geometry’ is not obligatory. You should put it only if explicitly placing window somewhere on the screen

      Full screen

      tk.attributes("-fullscreen", True) # substitute `Tk` for whatever your `Tk()` object is called

       

      Puis, on écoute la touche [ESC] sur le widget :

       

      tk.attributes("-fullscreen", False)

       

      Exemple avec [F11] to toggle fullscreen on and off and where escape will turn it off only :

       

      import sys
      from tkinter import *
      
      class Fullscreen_Window:
      
          def __init__(self):
              self.tk = Tk()
              self.tk.attributes('-zoomed', True) # just maximizes it so we can see the window. nothing to do with fullscreen.
              self.frame = Frame(self.tk)
              self.frame.pack()
              self.state = False
              self.tk.bind("<F11>", self.toggle_fullscreen)
              self.tk.bind("<Escape>", self.end_fullscreen)
      
          def toggle_fullscreen(self, event=None):
              self.state = not self.state  # Just toggling the boolean
              self.tk.attributes("-fullscreen", self.state)
              return "break"
      
          def end_fullscreen(self, event=None):
              self.state = False
              self.tk.attributes("-fullscreen", False)
              return "break"
      
      if __name__ == '__main__':
          w = Fullscreen_Window()
          w.tk.mainloop()

       

      If you want to hide a menu, too, there are only two ways I’ve found to do that. One is to destroy it. The other is to make a blank menu to switch between.

       

      self.tk.config(menu=self.blank_menu) # self.blank_menu is a Menu object

       

      Then switch it back to your menu when you want it to show up again.

       

      self.tk.config(menu=self.menu) # self.menu is your menu.

      BACKGROUND

      w.configure(bg='black')

      TEXTE

      On peut affecter une variable tkinter à un widget, avec textvariable, comme argument kwargs. Ensuite suffit de modifier..

       

      import tkinter as tk
      fenetre = tk.Tk()
      
      variable_a_modifier = tk.StringVar() # String
      #variable_a_modifier = tk.IntVar() # Integer
      #variable_a_modifier = tk.DoubleVar() # Float
      
      label = tk.Label(fenetre, textvariable=variable_a_modifier).pack()
      
      def modifier_texte():
         variable_a_modifier.set('Salut, ça va bien?') # .set() pour modifier la valeur de la variable
      
      btn_modifier = tk.Button(fenetre, text="Modifier", command=modifier_texte).pack()
      
      def print_texte():
         print( variable_a_modifier.get() ) # .get() pour récupérer la valeur de la variable
      
      btn_print = tk.Button(fenetre, text="Printer", command=print_texte).pack()
      fenetre.mainloop()

      LES FRAMES

      Frame est une région rectangulaire dans la fenêtre.

      créer une séparation

      import Tkinter as tk
      w = tk.Tk()
      tk.Label(text="UN").pack()
      separator = tk.Frame(height=2, bd=1, relief='SUNKEN')
      separator.pack(fill=X, padx=5, pady=5)
      tk.Label(text="DEUX").pack()
      w.mainloop()

       

      window_id to get the window handle corresponding to the frame.

       

      frame = Frame(width=768, height=576, bg="", colormap="new")
      frame.pack()
      video.attach_window(frame.window_id())

      options

      background= ou bg= Couleur de l’arrière-plan

      borderwidth= ou bd= Épaisseur de la bordure (0)

      cursor= aspect du curseur de la souris (flèche par défaut)

      height= (0)

      highlightbackground= couleur de la bordure extérieure

      highlightcolor= ?

      highlightthickness= Epaisseur de la bordure extérieure (0)

      padx= pady= padding horizontal, horizontal (0)

      relief= Décoration de la bordure : flat (défaut), sunken, raised, groove et ridge. NOTE: pour afficher la bordure, renseigner le bd=.

      takefocus= si true, la navigation par la touche TAB est possible (flase par défaut)

      visual= ?

      width= largeur (0)

      LES POPUPS

      Toplevel() est une fenêtre secondaire, identique au fenêtre normal, mais sans boucle (pas de mainloop)

       

      import tkinter as tk
      w = tk.Tk()
      
      def fenetre_secondaire():
      def retourner():
      ## Détruit la fenêtre secondaire
      secondaire.destroy()
      ## Remet la fenêtre principale en avant-plan
      w.deiconify()
      ## Permet de réduire la fenêtre principale
      w.withdraw()
      secondaire = tk.Toplevel()
      buttonA = tk.Button(secondaire, text='Retourner', command=retourner).pack()
      buttonB = tk.Button(secondaire, text='Quitter', command=secondaire.destroy).pack()
      button = tk.Button(w, text='AutreFenetre', command=fenetre_secondaire).pack()
      w.mainloop()
      tkinter.messagebox # permet d'afficher des Popups, de type Warning,Stop,AskYesorNo, ...

       

      import tkinter as tk
      import tkinter.messagebox as tkMB
      root = tk.Tk()
      def affichez_popup():
          question = tkMB.askquestion('Bonjour', 'Ça va bien?')
      is_ok = tkMB.showinfo('Salut', 'Ceci est un Carton Rouge, Sortez!')
      print(question)
      print(is_ok)
      button = tk.Button(root, text='Appuyez', command=affichez_popup).pack()
      root.mainloop()

       

      Voici le site, avec toutes les popups.

       

      .after() rappelle une fonction chaque X seconde. (ou ferme la fenêtre après X secondes)

      Il y a deux after() : une va détruire la fenêtre après 10s, à l’ouverture - l’autre va recommencer la fonction à chaque 1000 ms (1sec), une fois que vous aurez cliqué sur le bouton.

       

      import tkinter as tk
      import random
      COULEURS = ['red', 'blue', 'green', 'pink', 'white', 'black', 'grey']
      TEXTES_A = ['Salut', 'Coucou', 'Allo', 'Bonjour', 'Surpriseee']
      TEXTES_B = ['Bye', 'Cya', 'Aurevoir', 'Astala Vista', 'Ciao']
      fenetre = tk.Tk()
      varA = tk.StringVar()
      labelA = tk.Label(fenetre, textvariable=varA)
      labelA.pack()
      labelB = tk.Label(fenetre)
      labelB.pack()
      def commencez():
          choixA = random.choice(COULEURS)
          choixB = random.choice(TEXTES_A)
          choixC = random.choice(TEXTES_B)
      varA.set(choixB)
      labelB.config(text=choixC)
      bouton.config(bg=choixA)
      ## Aussitôt appuyez sur le bouton, on change les choix
      ## On répète la fonction.
      fenetre.after(1000, commencez)
      
      bouton = tk.Button(fenetre, text="Appuyez", command=commencez).pack()
      ## Aussitôt la fenêtre créé, on détruit fenêtre 10 secondes après.
      fenetre.after(10000, fenetre.destroy)
      fenetre.mainloop()

       

      Sauf que ici, il y a un problème. Puisque la fonction va continuer à l’infinie. Il n’arrêtera jamais de recommencer. Donc, si vous re-appuyez sur le bouton, vous enclenchez un autre callback, par dessus l’ancien. Donc, il va changer 2x en 1seconde. Jusqu’à l’infinie..

      Ce qui rend le programme lourd, si vous vous en rendez pas compte.

       

      Ne jamais créer de canvas/widgets dans une boucle qui se répète sinon, bonne chance

      Vous devez modifier/configurer les widgets/variables uniquement.

       

      Donc, si j’ajoute une variable pour l’arrêter, voici ce qui pourrait être envisagé.

       

      import tkinter as tk
      import random
      COULEURS = ['red', 'blue', 'green', 'pink', 'white', 'black', 'grey']
      TEXTES_A = ['Salut', 'Coucou', 'Allo', 'Bonjour', 'Surprizzz']
      TEXTES_B = ['Bye', 'Cya', 'Aurevoir', 'Astala Vista', 'Ciao']
      fenetre = tk.Tk()
      varA = tk.StringVar()
      labelA = tk.Label(fenetre, textvariable=varA)
      labelA.pack()
      labelB = tk.Label(fenetre)
      labelB.pack()
      CONTINUEZ = True
      
      def commencez():
          choixA = random.choice(COULEURS)
          choixB = random.choice(TEXTES_A)
          choixC = random.choice(TEXTES_B)
      varA.set(choixB)
      labelB.config(text=choixC)
      bouton.config(bg=choixA)
      if CONTINUEZ:
          fenetre.after(1000, commencez)
      
      def arretez():
          global CONTINUEZ
          CONTINUEZ = False
      
      bouton = tk.Button(fenetre, text="Appuyez", command=commencez).pack()
      bouton_arret = tk.Button(fenetre, text='Arretez', command=arretez).pack()
      fenetre.after(10000, fenetre.destroy)
      
      fenetre.mainloop()

       

      Comme cela, il arrêtera, quand vous le voudrez.

      VOIR AUSSI :

      https://www.python-course.eu/tkinter_text_widget.php

      https://python-django.dev/page-tkinter-interface-graphique-python-tutoriel

       

      from tkinter import *
      w = Tk()
      
      def make_label(master, x, y, h, w, *args, **kwargs):
          f = Frame(master, height=h, width=w)
          f.pack_propagate(0) # don't shrink
          f.place(x=x, y=y)
          label = Label(f, *args, **kwargs)
          label.pack(fill=BOTH, expand=1)
          return label
      
      make_label(w, 10, 10, 10, 40, text='xxx', background='red')
      make_label(w, 30, 40, 10, 30, text='xxx', background='blue')
      root.mainloop()

      GRID

       

      NOTE: Ne jamais mélanger du pack avec du grid dans la même fenêtre

       

      Label(w, text="First").grid(row=0)  # par défaut column=0
      Label(w, text="Second").grid(row=1) # par défaut column=0
      e1 = Entry(w)
      e2 = Entry(w)
      e1.grid(row=0, column=1)
      e2.grid(row=1, column=1)

       

       

      NOTES : Les lignes et colonnes vides seront ignorées. Les widgets sont centrés dans leurs cellules. On utilise sticky pour changer ce comportement (N, S, E, W)

       

      Label(master, text="First").grid(row=0, sticky=W)
      Label(master, text="Second").grid(row=1, sticky=W)
      e1 = Entry(master)
      e2 = Entry(master)
      e1.grid(row=0, column=1)
      e2.grid(row=1, column=1)

       

       

      columnspan pour étendre un widget sur plusieurs colonnes et rowspan pour les lignes :

       

      label1.grid(sticky=E)
      label2.grid(sticky=E)
      entry1.grid(row=0, column=1)
      entry2.grid(row=1, column=1)
      checkbutton.grid(columnspan=2, sticky=W)
      image.grid(row=0, column=2, columnspan=2, rowspan=2, sticky=W+E+N+S, padx=5, pady=5)
      button1.grid(row=2, column=2)
      button2.grid(row=2, column=3)

       

      options

      column= n° de la colonne (commence à 0)

      columnspan= étendue en colonnes du widget

      padx= padding horizontal - ipadx= padding horizontal (comme padx, mais le padding est inside)

      pady= padding vertical - ipady= padding vertical. Works like pady, mais le padding est inside)

      row= n° de la ligne (commence à 0). Si non renseigné, sera positionné à la première ligne libre.

      rowspan= étendue en ligne du widget

      sticky= Où faire coller le widget (centré par défaut)  : s,n,e, W, NW, NE, SW et SE.W+E pour remplir horizonalement. W+E+N+S pour remplir toute la cellule

      Options pour une colonne

      grid_columnconfigure(index_de_la_colonne, options)

       

      minsize= taille minimum de la colonne (note. Note that if a column is completely empty, it will not be displayed, even if this option is set.

      pad= Padding to add to the size of the largest widget in the column when setting the size of the whole column.

      weight= A relative weight used to distribute additional space between columns. A column with the weight 2 will grow twice as fast as a column with weight 1. The default is 0, which means that the column will not grow at all.

      grid_forget() Remove this widget from the grid manager. The widget is not destroyed, and can be displayed again by grid

      grid_remove() Remove this widget from the grid manager. The widget is not destroyed, and can be displayed again by grid

      grid_info() Return a dictionary containing the current cell options for the cell used by this widget.

      grid_location(x, y) Returns the grid cell under (or closest to) a given pixel. Returns: A tuple containing the column and row index.

      grid_propagate(flag) autorise ou pas la geometry propagation. Si oui, a grid manager connected to this widget attempts to change the size of the widget whenever a child widget changes size. Propagation is always enabled by default. flag True to enable propagation.

      Options pour une ligne

      grid_rowconfigure(index_de_la_ligne, **options)

       

      minsize= taille minimale. NOTE : si aucun élément présent, la ligne ne sera pas visible.

      pad= padding

      weight= distribute additional space between rows. A row with the weight 2 will grow twice as fast as a row with weight 1. (défaut 0 = row will not grow at all).

      grid_size() renvoie la taille de la ligne concernée. Returns: A 2-tuple containing the number of columns and rows.

      grid_slaves(row=None, column=None) renvoie une liste de “slave” widgets managed by this widget. The widgets are returned as Tkinter widget references.

      Returns: A list of widgets.

      PACK

      pack permet de:

      - Placer un widget dans une frame (ou autre container), et remplir ce dernier

      - Placer un nombre de widgets l’un au-dessus de l’autre

      - Placer un nombre de widgets côte-à-côte

      Remplir un widget parent

      Pour remplir entièrement un widget parent, même si l’utilisateur modifie la taille grâce à fill et expand :

       

      from Tkinter import *
      root = Tk()
      listbox = Listbox(root)
      listbox.pack(fill=BOTH, expand=1)
      for i in range(20):
          listbox.insert(END, str(i))
      mainloop()

       

       

      fill=BOTH pour étendre le widget horisontally and vertically (sinon, X pour horizontalement, et Y vertically)

      expand=1 assigne additional space to the widget box. If the parent widget is made larger than necessary to hold all packed widgets, any exceeding space will be distributed among all widgets that have the expand option set to a non-zero value.

      Placer des widgets les uns au-dessus des autres

      root = Tk()
      
      w = Label(root, text="Red", bg="red", fg="white")
      w.pack()
      w = Label(root, text="Green", bg="green", fg="black")
      w.pack()
      w = Label(root, text="Blue", bg="blue", fg="white")
      w.pack()

       

       

      fill=X pour remplir l’espace horizontalement:

       

      root = Tk()
      
      w = Label(root, text="Red", bg="red", fg="white")
      w.pack(fill=X)
      w = Label(root, text="Green", bg="green", fg="black")
      w.pack(fill=X)
      w = Label(root, text="Blue", bg="blue", fg="white")
      w.pack(fill=X)

       

      Placer des widgets les uns à côté des autres

      side= Pour rendre le widget aussi haut que le parent, use the fill=Y option too:

       

      root = Tk()
      
      w = Label(root, text="Red", bg="red", fg="white")
      w.pack(side=LEFT)
      w = Label(root, text="Green", bg="green", fg="black")
      w.pack(side=LEFT)
      w = Label(root, text="Blue", bg="blue", fg="white")
      w.pack(side=LEFT)

       

      options

      pack(options)

       

      anchor= Endroit où le widget est placé à l’intérieur : n, s, e, w, center (défaut).

      expand= Spécifie si les widgets doivent être étendus to fill any extra space in the geometry master. If false (default), the widget is not expanded.

      fill= comment remplir l’espace : NONE (default), X (horizontal), Y (vertical), ou BOTH (remplir totalement le widget) avec expand to a non-zero value.

      in= Pack this widget inside the given widget. You can only pack a widget inside its parent, or in any decendant of its parent. This option should usually be left out, in which case the widget is packed inside its parent.
      Note that in is a reserved word in Python. To use it as a keyword option, append an underscore (in_).

      padx= pady= padding externe (0) ipadx= ipady= padding interne (0)

      side= sur quel côté doit coller le widget. TOP (default), LEFT, BOTTOM et RIGHT

       

      pack_configure(options)

       

      pack_forget() Retirer le widget. Pour le replacer, réinvoquer pack().

      pack_info() Retourne les options actuelles.

      pack_propagate(flag) Controls geometry propagation. If enabled, the manager widget will be resized if not large enough to hold all the child widgets.Note that this method should be called on the master widget, not on an invidivual child widget.

      pack_slaves() Retourne la liste des enfants (slave) du parent.

      Place

      Renseigne la position et la taille d’une fenêtre, soit en mode absolue, soit en relatif.

       

      Centrer un enfant dans son parent :

       

      w.place(relx=0.5, rely=0.5, anchor=CENTER)

       

      Placer un Label dans une Frame, et place un Button dans le coin supérieur droit de la frame. Le button chevauchera le label :

       

      pane = Frame(master)
      Label(pane, text='Pane Title').pack()
      b = Button(pane, width=12, height=12, image=launch_icon, command=self.launch)
      b.place(relx=1, x=-2, y=2, anchor='NE')

       

      The following excerpt from a Notepad widget implementation displays a notepad page (implemented as a Frame) in the notepad body frame. It first loops over the available pages, calling place_forget for each one of them. Note that it’s not an error to “unplace” a widget that it’s not placed in the first case:

       

      for w in self.__pages:
          w.place_forget()
      self.__pages[index].place(in_=self.__body, x=bd, y=bd)

       

      You can combine the absolute and relative options. In such cases, the relative option is applied first, and the absolute value is then added to that position. In the following example, the widget w is almost completely covers its parent, except for a 5 pixel border around the widget.

      w.place(x=5, y=5, relwidth=1, relheight=1, width=-10, height=-10)

       

      You can also place a widget outside another widget. For example, why not place two widgets on top of each other:

      w2.place(in_=w1, relx=0.5, y=-2, anchor=S, bordermode="outside")

       

      Note the use of relx and anchor options to center the widgets vertically. You could also use (relx=0, anchor=SW) to get left alignment, or (relx=1, anchor=SE) to get right alignment.

      By the way, why not combine this way to use the packer with the launch button example shown earlier. The following example places two buttons in the upper right corner of the pane:

      b1 = DrawnButton(pane, (12, 12), launch_icon, command=self.launch)
      b1.place(relx=1, x=-2, y=2, anchor=NE)
      b2 = DrawnButton(pane, (12, 12), info_icon, command=self.info)
      b2.place(in_=b1, x=-2, anchor=NE, bordermode="outside")

       

      Finally, let’s look at a piece of code from an imaginary SplitWindow container widget. The following piece of code splits frame into two subframes called f1 and f2.

      f1 = Frame(frame, bd=1, relief=SUNKEN)
      f2 = Frame(frame, bd=1, relief=SUNKEN)
      split = 0.5
      f1.place(rely=0, relheight=split, relwidth=1)
      f2.place(rely=split, relheight=1.0-split, relwidth=1)

       

      To change the split point, set split to something suitable, and call the place method again. If you haven’t changed an option, you don’t have to specify it again.

      f1.place(relheight=split)
      f2.place(rely=split, relheight=1.0-split)

       

      You could add a small frame to use as a dragging handle, and add suitable bindings to it, e.g:

      f3 = Frame(frame, bd=2, relief=RAISED, width=8, height=8)
      f3.place(relx=0.9, rely=split, anchor=E)
      f3.bind("B1-Motion>", self.adjust)

      options

      place(options)

       

      anchor= n,e,s,w. Default is NW.

      bordermode= Default is INSIDE.

      height= No default value.

      in= Default is ..

      relheight= No default value.

      relwidth= No default value.

      relx= Default is 0.

      rely= Default is 0.

      width= No default value.

      x= Default is 0.

      y= Default is 0.

      place_configure(**options) Same as place.

      place_forget() The place_forget method.

      place_info() The place_info method.

      place_slaves() The place_slaves method.

      slaves() Same as place_slaves.

      Toplevel

      work pretty much like Frame, but it is displayed in a separate, top-level window. Such windows usually have title bars, borders, and other “window decorations”.

      The Toplevel widget is used to display extra application windows, dialogs, and other “pop-up” windows.

       

      top = Toplevel()
      top.title("About this application...")
      
      msg = Message(top, text=about_message)
      msg.pack()
      
      button = Button(top, text="Dismiss", command=top.destroy)
      button.pack()

       

       

      Toplevel(master=None, **options).

       

      master Parent widget.

      config(**options) Modifies one or more widget options. If no options are given, the method returns a dictionary containing all current option values.

      background= ou bg= couleur de l’arrière-plan

      borderwidth= ou bd= Width of the 3D border. Defaults to 0

      class= Default value is Toplevel.

      colormap= Some displays support only 256 colors (some use even less). Such displays usually provide a color map to specify which 256 colors to use. This option allows you to specify which color map to use for this toplevel window, and its child widgets. By default, a new toplevel window uses the same color map as the root window. Using this option, you can reuse the color map of another window instead (this window must be on the same screen and have the same visual characteristics). You can also use the value “new” to allocate a new color map for this window. You cannot change this option once you’ve created the window.

      container= Default value is 0.

      cursor= The cursor to show when the mouse pointer is located over the toplevel widget. Default is a system specific arrow cursor.

      height= Window height, in pixels. If omitted, the widget is made large enough to hold its contents.

      highlightbackground= The color to use for the highlight region when the widget doesn’t have focus. The default is system specific.

      highlightcolor= The color to use for the highlight region when the widget has focus. The default is system specific.

      highlightthickness= The width of the highlight region. Default is 0 (no region).

      menu= A menu to associate with this toplevel window. On Unix and Windows, the menu is placed at the top of the toplevel window itself. On Macs, the menu is displayed at the top of the screen when the toplevel window is selected.

      padx= Horizontal padding. Default is 0

      pady= Vertical padding. Default is 0

      relief= Border decoration: either FLAT, SUNKEN, RAISED, GROOVE, or RIDGE. The default is FLAT

      screen= No default value

      takefocus= Indicates that the user can use the Tab key to move to this widget. Default is false.

      use= No default value.

      visual= Controls the “visual” type to use for this window. This option should usually be omitted. In that case, the visual type is inherited from the root window.
      Some more advanced displays support “mixed visuals”. This typically means that the root window is a 256-color display (the “pseudocolor” visual type), but that individual windows can be displayed as true 24-bit color (the “truecolor” visual type). On such displays, you may wish to explicitly set the visual option to “truecolor” for any windows used to display full-color images. Other possible values include “directcolor”, “staticcolor”, “grayscale”, or “staticgray”. See your X window documentation for details. You cannot change this option once you’ve created the window.

      width= Window width, in pixels. If omitted, the widget is made large enough to hold its contents.

      PanedWindow

      PanedWindow can contain one or more child widgets (“panes”). The child widgets can be resized by the user, by moving separator lines (“sashes”) using the mouse. The PanedWindow widget can be used to implement common 2-pane and 3-pane layouts.

       

      m = PanedWindow(orient=VERTICAL)
      m.pack(fill=BOTH, expand=1)
      top = Label(m, text="top pane")
      m.add(top)
      bottom = Label(m, text="bottom pane")
      m.add(bottom)

       

      Here’s how to create a 3-pane widget:

      m1 = PanedWindow()
      m1.pack(fill=BOTH, expand=1)
      left = Label(m1, text="left pane")
      m1.add(left)
      m2 = PanedWindow(m1, orient=VERTICAL)
      m1.add(m2)
      top = Label(m2, text="top pane")
      m2.add(top)
      bottom = Label(m2, text="bottom pane")
      m2.add(bottom)

       

      PanedWindow(master=None, **options)

       

      master Parent widget.

      add(child, **options) Adds a child window to the paned window.

      config(**options) Modifies one or more widget options. If no options are given, the method returns a dictionary containing all current option values.

      background= ou bg= Default is system specific. (background/Background)

      borderwidth= ou bd= Default is 2

      cursor= No default value

      handlepad= Default is 8

      handlesize= Default is 8

      height= No default value

      opaqueresize= No default value

      orient= Default is HORIZONTAL

      relief= Default is FLAT

      sashcursor= No default value

      sashpad= Default is 2

      sashrelief= Default is RAISED

      sashwidth= Default is 2

      showhandle= No default value

      width= No default value

      forget(child) Removes a child window.

      identify(x, y) Identifies the widget element at the given position.

      panecget(child, option) Gets a child window option.

      paneconfig(child, **options) Set child window configuration options.

      child Child window.

      after= Insert after this widget.

      before= Insert before this widget.

      height= Widget height.

      minsize= Minimal size (width for horizontal panes, height for vertical panes).

      padx= Horizontal padding.

      pady= Vertical padding.

      sticky= Defines how to expand a child widget if the resulting pane is larger than the widget itself. S, N, E et W  or NW, NE, SW, and SE.

      width= Widget width.

      panes() Returns a list of child widgets. Returns: A list of widgets.

      proxy_coord() Gets the most recent proxy position.

      proxy_forget() Removes the proxy.

      proxy_place(x, y) Places the proxy at the given position.

      remove(child) Same as forget.

      sash_coord(index) Gets the current position for a sash (separator).

      index Sash index (0..n).

      Returns: The upper left corner of the sash, given as a 2-tuple (x, y).

      sash_dragto(index, x, y) Drag the sash (separator) to a new position, relative to the mark. Together with sash_mark, this method is used by the widget bindings to move a sash by dragging the mouse. The mark method is called when the mouse is pressed over a sash (you can use identify to figure out which sash to mark), and the dragto method is called repeatedly when the mouse pointer is moved.

      Note that this method is missing from the Tkinter bindings in Python 2.3. You can use sash("dragto", index, x, y) instead.

      index Sash index (0..n). Returns: The upper left corner of the sash, given as a 2-tuple (x, y).

      sash_mark(index, x, y) Registers the current mouse position. See sash_dragto for more information. Note that this method only takes a single argument in the Tkinter bindings shipped with in Python 2.3. To pass in all three arguments, use sash("mark", index, x, y)

      index Sash index (0..n) - x Start position. - y Start position.

      sash_place(index, x, y) Moves the sash (separator) to a given position.

      index Sash index (0..n). - x Sash position. - y Sash position.

      Scrollbar

      Pour une scrolled listboxes, canvases, and text fields. Scrollbar is almost always used in conjunction with Listbox, Canvas, or Text. Horizontal scrollbars can also be used with the Entry widget.

      To connect a vertical scrollbar to such a widget, you have to do two things:

      - Set the widget’s yscrollcommand callbacks to the set method of the scrollbar.

      - Set the scrollbar’s command to the yview method of the widget.

       

      w = Tk()
      scrollbar = Scrollbar(w)
      scrollbar.pack(side=RIGHT, fill=Y)
      
      listbox = Listbox(w, yscrollcommand=scrollbar.set)
      for i in range(1000):
          listbox.insert(END, str(i))
      listbox.pack(side=LEFT, fill=BOTH)
      
      scrollbar.config(command=listbox.yview)

       

      When the widget view is modified, the widget notifies the scrollbar by calling the set method. And when the user manipulates the scrollbar, the widget’s yview method is called with the appropriate arguments.

      Adding a horizontal scrollbar is as simple. Just use the xscrollcommand option instead, and the xview method.

       

      Scrollbar(master=None, **options)

      master Parent widget.

      activate(element) Activates a scrollbar element. element The scrollbar element to activate. Use one of “arrow1”, “slider”, or “arrow2”. If omitted, the method returns the currently active element, or an empty string if no element is active.

      config(**options) Modifies one or more widget options. If no options are given, the method returns a dictionary containing all current option values.

      activebackground= Default value is system specific

      activerelief= Default value is RAISED.

      background= ou bg= Default value is system specific.

      borderwidth= ou bd= Border width. Default value is 0

      command= A callback used to update the associated widget. This is typically the xview or yview method of the scrolled widget.
      If the user drags the scrollbar slider, the command is called as callback(“moveto”, offset), where offset 0.0 means that the slider is in its topmost (or leftmost) position, and offset 1.0 means that it is in its bottommost (or rightmost) position.
      If the user clicks the arrow buttons, or clicks in the trough, the command is called as callback(“scroll”, step, what). The second argument is either “-1” or “1” depending on the direction, and the third argument is “units” to scroll lines (or other unit relevant for the scrolled widget), or “pages” to scroll full pages.

      cursor= The cursor to show when the mouse pointer is placed over the scrollbar widget. Default is a system specific arrow cursor.

      elementborderwidth= Default value is -1.

      highlightbackground= Together with highlightcolor and highlightthickness, this option controls how to draw the highlight border. When the widget has focus, a highlightthickness-wide border is drawn in the highlightcolor color. Otherwise, it is drawn in the highlightbackground color. The default colors are system specific

      highlightcolor=

      highlightthickness= See highlightbackground. Default value is 0.

      jump= Default value is 0.

      orient= Defines how to draw the scrollbar. Use one of HORIZONTAL or VERTICAL. Default is VERTICAL

      relief= Border decoration. The default is SUNKEN. Other possible values are FLAT, RAISED, GROOVE, and RIDGE. This option is ignored under Windows.

      repeatdelay= Default value is 300.

      repeatinterval= Default value is 100.

      takefocus= Default is an empty string.

      troughcolor= Default value is system specific.

      width= Scrollbar width, in pixels. Default value is 16.

      delta(deltax, deltay) Returns a floating point number that should be added to the current slider offsets in order to move the slider the given number of pixels. This is typically used by the mouse bindings to figure out how to move the slider when the user is dragging it around.

      deltax Horizontal delta, in screen coordinates. deltay Vertical delta, in screen coordinates.

      Returns: Value to add to the scrollbar offset.

      fraction(x, y) Returns the slider position corresponding to a given mouse coordinate.

      x Horizontal screen coordinate. y Vertical screen coordinate.

      Returns: The scrollbar offset corresponding to the given coordinate (0.0 through 1.0).

      get() Gets the current slider position. Returns: A tuple containing the relative offset for the upper (leftmost) and lower (rightmost) end of the scrollbar slider. Offset 0.0 means that the slider is in its topmost (or leftmost) position, and offset 1.0 means that it is in its bottommost (or rightmost) position.

      identify(x, y) Identifies the scrollbar element at the given location. x Horizontal screen coordinate. y Vertical screen coordinate.

      Returns: One of “arrow1” (top/left arrow), “trough1”, “slider”, “trough2”, “arrow2” (bottom/right), or an empty string for any other part of the scrollbar widget.

      set(lo, hi) Moves the slider to a new position.

      lo The relative offset for the upper (leftmost) end of the scrollbar slider.

      hi The relative offset for the lower (rightmost) end of the the scrollbar slider.

      Toplevel Window Methods

      methods to communicate with the window manager. They are available on the root window (Tk), as well as on all Toplevel instances.

      Note that different window managers behave in different ways. For ex, some window managers don’t support icon windows, some don’t support window groups, etc.

       

      Wm Wm implementation class. This class is used as a mixin by the root (Tk) and Toplevel widgets.

      aspect(minNumer=None, minDenom=None, maxNumer=None, maxDenom=None) Controls the aspect ratio (the relation between width and height) of this window. The aspect ratio is constrained to lie between minNumer/minDenom and maxNumer/maxDenom.

      If no arguments are given, this method returns the current constraints as a 4-tuple, if any.

      attributes(*args) Sets or gets window attributes. In Python 2.4, this wrapper is incomplete, and the application must use a non-standard syntax to modify and query the available attributes.

      *args One or more attribute specifiers. The current version doesn’t support keyword arguments. Instead, you have to prefix the attribute name with a hyphen, and pass in the value as a separate argument (e.g. to set the “disabled” option, use attribute(“-disabled”, 1) instead of attribute(disabled=1)). If only an attribute name is given, the method returns the current value. If no arguments are given, the method returns the current attribute settings (see below for details).

      alpha= (Windows, Mac) Controls window transparency. 0.0 means fully transparent, 1.0 means fully opaque. This isn’t supported on all systems; where not supported, Tkinter always uses 1.0. Note that in this release, this attribute must be given as “-alpha”.

      disabled= (Windows) If set, disables the entire window. Note that in this release, this attribute must be given as “-disabled”.

      modified= (Mac) If set, the window is flagged as modified. Note that in this release, this attribute must be given as “-modified”.

      titlepath= (Mac) The path to the window proxy icon. Note that in this release, this attribute must be given as “-titlepath”.

      toolwindow= (Windows) If set, sets the window style to a “tool window”. Note that in this release, this attribute must be given as “-toolwindow”.

      topmost= (Windows) If set, this window is always placed on top of other windows. Note that in this release, this attribute must be given as “-topmost”.

      Returns: If an attribute value was specified, the return value is undefined. If a single attribute name was specified, this is the current attribute value (as a string). If no arguments where specified, this currently returns the current attribute values as a string, in the format “-attribute value -attribute value”. Future versions may return a dictionary instead.

      client(name=None) Sets or gets the WM_CLIENT_MACHINE property. This property is used by window managers under the X window system. It is ignored on other platforms. To remove the property, set it to an empty string.

      name The new value for this property. If omitted, the current value is returned.

      colormapwindows(*wlist) Sets or gets the WM_COLORMAP_WINDOWS property. This property is used by window managers under the X window system. It is ignored on other platforms.

      wlist The new value for this property. If omitted, the current value is returned.

      command(value=None) Sets or gets the WM_COMMAND property. This property is used by window managers under the X window system. It is ignored on other platforms.

      wlist The new value for this property. If omitted, the current value is returned. To remove the property, pass in an empty string.

      deiconify() Displays the window. New windows are displayed by default, so you only have to use this method if you have used iconify or withdraw to remove the window from the screen.

      focusmodel(model=None) Sets or gets the focus model.

      frame() Returns a string containing a system-specific window identifier corresponding to the window’s outermost parent. For Unix, this is the X window identifier. For Windows, this is the HWND cast to a long integer. Note that if the window hasn’t been reparented by the window manager, this method returns the window identifier corresponding to the window itself.

      geometry(geometry=None) Sets or gets the window geometry. If called with an argument, this changes the geometry. The argument should have the following format:

      "%dx%d%+d%+d" % (width, height, xoffset, yoffset)

      To convert a geometry string to pixel coordinates, you can use something like this:

      import re
      def parsegeometry(geometry):
          m = re.match("(\d+)x(\d+)([-+]\d+)([-+]\d+)", geometry)
          if not m:
              raise ValueError("failed to parse geometry string")
          return map(int, m.groups())

      geometry The new geometry setting. If omitted, the current setting is returned.

      grid(baseWidth=None, baseHeight=None, widthInc=None, heightInc=None) The grid method.

      group(window=None) Adds window to the window group controlled by the given window. A group member is usually hidden when the group owner is iconified or withdrawn (the exact behavior depends on the window manager in use).

      window The group owner. If omitted, the current owner is returned.

      iconbitmap(bitmap=None) Sets or gets the icon bitmap to use when this window is iconified. This method is ignored by some window managers (including Windows).  Note that this method can only be used to display monochrome icons. To display a color icon, put it in a Label widget and display it using the iconwindow method instead.

      iconify() Turns the window into an icon (without destroying it). To redraw the window, use deiconify. Under Windows, the window will show up in the taskbar.

      When the window has been iconified, the state method returns “iconic”.

      iconmask(bitmap=None) Sets or gets the icon bitmap mask to use when this window is iconified. This method is ignored by some window managers (including Windows).

      iconname(newName=None) Sets or gets the icon name to use when this window is iconified. This method is ignored by some window managers (including Windows).

      iconposition(x=None, y=None) Sets or gets the icon position hint to use when this window is iconified. This method is ignored by some window managers (including Windows).

      iconwindow(window=None) Sets or gets the icon window to use as an icon when this window is iconified. This method is ignored by some window managers (including Windows).

      window The new icon window. If omitted, the current window is returned.

      maxsize(width=None, height=None) Sets or gets the maximum size for this window.

      minsize(width=None, height=None) Sets or gets the minimum size for this window.

      overrideredirect(flag=None) Sets or gets the override redirect flag. If non-zero, this prevents the window manager from decorating the window. In other words, the window will not have a title or a border, and it cannot be moved or closed via ordinary means.

      positionfrom(who=None) Sets or gets the position controller

      protocol(name=None, func=None) Registers a callback function for the given protocol. The name argument is typically one of “WM_DELETE_WINDOW” (the window is about to be deleted), “WM_SAVE_YOURSELF” (called by X window managers when the application should save a snapshot of its working set) or “WM_TAKE_FOCUS” (called by X window managers when the application receives focus).

      resizable(width=None, height=None) Sets or gets the resize flags. The width flag controls whether the window can be resized horizontally by the user. The height flag controls whether the window can be resized vertically.

      sizefrom(who=None) Sets or gets the size controller

      state(newstate=None) Sets or gets the window state. This is one of the values “normal”, “iconic” (see iconify, “withdrawn” (see withdraw) or “icon” (see iconwindow).

      title(string=None) Sets or gets the window title.

      title The new window title. If omitted, the current title is returned.

      transient(master=None) Makes window a transient window for the given master (if omitted, master defaults to self’s parent). A transient window is always drawn on top of its master, and is automatically hidden when the master is iconified or withdrawn. Under Windows, transient windows don’t show show up in the task bar.

      withdraw() Removes the window from the screen (without destroying it). To redraw the window, use deiconify.

      When the window has been withdrawn, the state method returns “withdrawn”.

       

      LIENS

       

      http://effbot.org/tkinterbook/

       

      http://effbot.org/tkinterbook/tkinter-index.htm#class-reference

       

      https://www.fil.univ-lille1.fr/~marvie/python/chapitre6.html

       

      http://s15847115.domainepardefaut.fr/python/tkinter/menus.html

       

 

Aucun commentaire

 

Laissez un commentaire