IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Tkinter Python Discussion :

Canvas itemconfig trop lent


Sujet :

Tkinter Python

  1. #1
    Invité
    Invité(e)
    Par défaut Canvas itemconfig trop lent
    Bonjour,

    J'utilise un Canvas pour afficher une image et plusieurs textes en superposition (pour créer une ombre stylée), mon problème est de mettre à jour ces textes et d'afficher le Canvas une fois qu'ils sont mis à jour.
    Avec itemconfig je mets donc à jour chaque texte un après l'autre, ce qui donne un mauvais rendu visuel.

    J'ai ralenti pour que vous puissiez voir :
    Nom : Sans-titre---1.gif
Affichages : 871
Taille : 319,5 Ko

    Y a t il une manière de procéder qui permettrait de mettre à jour le canvas uniquement quand tout est prêt à être affiché ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    canvas = tk.Canvas(root, width = WIDTH, height = HEIGHT)    
     
    date = time.strftime('%A, %d %B, %Y %H:%M:%S').capitalize()
    date = date.split(' ')
    hour = date[-1]
    day = ' '.join((date[0:-1]))
     
    hour_b = canvas.create_text(int(WIDTH/2),int(HEIGHT/2)-50, font=('French Script MT', 200, 'bold'), fill='black', text = hour)
    hour_f = canvas.create_text(int(WIDTH/2),int(HEIGHT/2)-50, font=('French Script MT', 200), fill='white', text = hour)
    day_l = canvas.create_text(int(WIDTH/2)-1,int(HEIGHT/2)+90, font=('French Script MT', 50), fill='black', text = day)
    day_r = canvas.create_text(int(WIDTH/2)+1,int(HEIGHT/2)+90, font=('French Script MT', 50), fill='black', text = day)
    day_f = canvas.create_text(int(WIDTH/2),int(HEIGHT/2)+90, font=('French Script MT', 50), fill='white', text = day)
     
    canvas.pack()
    Plus loin dans une boucle :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
            date = time.strftime('%A, %d %B, %Y %H:%M:%S').capitalize()
            date = date.split(' ')
            hour = date[-1]
            day = ' '.join((date[0:-1]))
            canvas.itemconfig(hour_b, text=hour)
            canvas.itemconfig(hour_f, text=hour)
            canvas.itemconfig(day_l, text=day)
            canvas.itemconfig(day_r, text=day)
            canvas.itemconfig(day_f, text=day)
    Merci par avance !
    Dernière modification par Invité ; 15/08/2022 à 17h13.

  2. #2
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 778
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 778
    Par défaut
    Salut,

    Normalement, la mise à jour de l'affichage se fait dès la sortie du callback (sauf à le forcer avant via .update_idletasks).

    Maintenant, il est préférable de réduire le nombre d'appels (et de mises à jour successives):
    • mettre à jour toute la chaîne de caractère plutôt que des petits bouts,
    • sinon ne mettre à jour que ce qui change.


    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  3. #3
    Invité
    Invité(e)
    Par défaut
    Je ne comprends pas ce que je dois faire...

    Visiblement l'utilisation de la fonction itemconfig(tagOrId, option) rafraichit l'affichage, je voudrais l'empêcher en quelque sorte.
    Il y a peut-être moyen de mettre à jour le texte d'un Canvas sans passer par cette fonction ?µ

    PS : J'ai essayé de mettre plusieurs id dans la fonction itemconfigure mais ça ne marche pas...

  4. #4
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 778
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 778
    Par défaut
    Citation Envoyé par LeNarvalo Voir le message
    je voudrais l'empêcher en quelque sorte.
    Vous devez faire avec ce que propose tkinter (et le Canvas)... Et poster du code qui permette de reproduire (pas des bouts dont on ne sait ce qu'il y a autour).

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  5. #5
    Invité
    Invité(e)
    Par défaut
    Ca fait qq heures que je navigue sur ce site à la recherche d'une solution : http://tkinter.fdex.eu/doc/caw.html

    Le code est prévu pour Windows seulement :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    import time, threading, random, os
    import win32gui, win32con, win32api
    import ctypes
    import tkinter as tk
    from PIL import ImageTk, Image
    import locale
     
    locale.setlocale(locale.LC_TIME,'')
     
    ####PARAMETRES####
    IdleTime = 1000  #msec
     
    ####VARIABLES####
    wallpaper = None
    wallpaper_path = None
    wallpaperized = False
    idle = False
    win_title = 'WALLPAPER.py-'+str(random.getrandbits(128)) #Nom de fenêtre Tkinter random
    chemin = os.path.expanduser('~\Wallpaper')
     
    def getIdleTime():
        return (win32api.GetTickCount() - win32api.GetLastInputInfo())
     
    # Afficher le bureau quand on clic gauche sur le wallpaper
    def on_click(event):
        global idle
        root.withdraw()
        idle = False
     
    #Met à jour le canvas (si changement de wallpaper)
    def getWallpaper():
        global wallpaper, wallpaper_path
        ubuf = ctypes.create_unicode_buffer(512)
        ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_GETDESKWALLPAPER,len(ubuf),ubuf,0)
        path = ubuf.value
     
        if wallpaper_path != path:
            wallpaper_path = path
            wallpaper = Image.open(path)
            w, h = wallpaper.size
            ratio_w = w/WIDTH
            ratio_h = h/HEIGHT
            if ratio_w > ratio_h:
                W, H = (int(w/ratio_w), int(h/ratio_w))
                wallpaper = wallpaper.resize((W, H))
                black = Image.new('RGB', (WIDTH, HEIGHT), color = 'black')
                black.paste(wallpaper, (int((WIDTH-W)/2), int((HEIGHT-H)/2)))
                wallpaper = black.copy()
            elif ratio_w <= ratio_h:
                W, H = (int(w/ratio_h), int(h/ratio_h))
                wallpaper = wallpaper.resize((W, H))
                black = Image.new('RGB', (WIDTH, HEIGHT), color = 'black')
                black.paste(wallpaper, (int((WIDTH-W)/2), int((HEIGHT-H)/2)))
                wallpaper = black.copy()
     
            #wallpaper = ImageOps.fit(wallpaper, (WIDTH,HEIGHT)) #Redimensionne l'image à la taille de l'écran  
            wallpaper = ImageTk.PhotoImage(wallpaper)           #Transforme l'image pour Tkinter
            canvas.itemconfig(container, image=wallpaper)       #Met à jour le canvas
     
    #Affiche la fenêtre tkinter
    def displayWallpaper():    
        root.deiconify()    
     
    #TITLE = []
    #Retourne False si une fenêtre est ouverte (sauf root et qq programmes windows), une exception est alors soulevée par EnumWindows
    def winEnumHandler( hwnd, liste ):
        if win32gui.IsWindowVisible( hwnd ) and not win32gui.IsIconic(hwnd):
            title = win32gui.GetWindowText( hwnd )
            liste.append((hwnd, title))
            for word in ('','Expérience d’entrée Windows','Program Manager','Paramètres','Hôte contextuel',\
                         'Centre de notifications','Calculatrice','Alarmes et horloge','Drag','Pense-bêtes', 'Gestionnaire des tâches', win_title):
                if title == word:
                    break
                    #return True
            else:
                return False
     
    #Fenêtre tkinter
    def mainroot():
        global WIDTH, HEIGHT, root, container, canvas, canvas2, hour_b, hour_f, day_l, day_r, day_f
        root = tk.Tk()
        root.title(win_title)
     
        WIDTH, HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight()
        root.geometry(f'{WIDTH+4}x{HEIGHT+4}+-2+-2')    
        #root.attributes('-fullscreen',True )
        root.overrideredirect(1)                                                #Mettre la fenêtre par dessus tout
        #root.attributes('-topmost',True )
        canvas = tk.Canvas(root, width = WIDTH, height = HEIGHT)    
        container = canvas.create_image(2,2, anchor=tk.NW)                      #Garder le canvas en mémoire
     
        date = time.strftime('%A, %d %B, %Y %H:%M:%S').capitalize()
        date = date.split(' ')
        hour = date[-1]
        day = ' '.join((date[0:-1]))
     
        hour_b = canvas.create_text(int(WIDTH/2),int(HEIGHT/2)-50, font=('French Script MT', 200, 'bold'), fill='black', text = hour)
        hour_f = canvas.create_text(int(WIDTH/2),int(HEIGHT/2)-50, font=('French Script MT', 200), fill='white', text = hour)
        day_l =  canvas.create_text(int(WIDTH/2)-1,int(HEIGHT/2)+90, font=('French Script MT', 50), fill='black', text = day)
        day_r =  canvas.create_text(int(WIDTH/2)+1,int(HEIGHT/2)+90, font=('French Script MT', 50), fill='black', text = day)
        day_f =  canvas.create_text(int(WIDTH/2),int(HEIGHT/2)+90, font=('French Script MT', 50), fill='white', text = day)
     
        canvas.pack()
     
        root.withdraw()                                                         #Cacher la fenêtre
        root.bind("<ButtonRelease-1>", on_click)                                #"Binder" la fenêtre entière pour la cacher
        root.mainloop()
     
     
    threading.Thread(target=mainroot, daemon=True).start()
    time.sleep(1)
    while True:
        time.sleep(0.1)
        getWallpaper()
        try:
            liste = []
            win32gui.EnumWindows( winEnumHandler, liste )
        except:                                                                 #Une fenêtre est ouverte (exceptée celles autorisées)
            wallpaperized = False
            idle = False
        else:                                                                   #Si aucune exception soulevée alors aucune fenêtre n'est ouverte, on est donc sur le bureau grosso-modo
            title = win32gui.GetWindowText(win32gui.GetForegroundWindow())
     
            if not title:                                                       #On est vraiment sur le bureau
                if not wallpaperized:                                           #On n'a pas déjà affiché le wallpaper (sécurité inutile ?)
                    wallpaperized = True
                    threading.Thread(target=displayWallpaper, daemon=True).start()           #On affiche le wallpaper
     
            if not idle:
                if getIdleTime()>IdleTime :
                    idle = True
                    wallpaperized = True
                    threading.Thread(target=displayWallpaper, daemon=True).start()
                    #for fen in liste:
                    #    hwnd, titre = fen
                    #    if titre in ('Calculatrice','Alarmes et horloge','Pense-bêtes'):      #Afficher ces trois utilitaires windows par dessus le wallpaper
                     #       try:
                      #          win32gui.SetForegroundWindow(hwnd)
                      #      except:
                       #         print(titre,'failed to setforeground')
     
     
            date = time.strftime('%A, %d %B, %Y %H:%M:%S').capitalize()
            date = date.split(' ')
            hour = date[-1]
            day = ' '.join((date[0:-1]))
     
            canvas.itemconfig(hour_b, text=hour)
            canvas.itemconfig(hour_f, text=hour)
            canvas.itemconfig(day_l, text=day)
            canvas.itemconfig(day_r, text=day)
            canvas.itemconfig(day_f, text=day)
    Tkinter propose bien des solutions pour mettre à jour l'affichage avant que les opérations ne soient achevées avec update_idletasks() mais c'est tout l'inverse que je voudrais...
    J'ai essayé d'utiliser un wait_variable(v) sans succès. J'ai aussi essayé de cacher / réafficher les textes mais c'est pire...

    PS : Pour voir le script, il suffit d'aller sur le bureau de Windows et de ne rien faire pendant environ 1 seconde.
    PS2 : Oops, code mis à jour, il y avait une boulette...
    Dernière modification par Invité ; 15/08/2022 à 18h11.

  6. #6
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 778
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 778
    Par défaut
    Salut,

    Ce n'est pas de la programmation tkinter "normale".... aucune des recommandations précédentes ne sont appliquées: débrouillez vous (sans moi).

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  7. #7
    Membre chevronné Avatar de licardentaistor
    Homme Profil pro
    Administrateur de base de données
    Inscrit en
    Juillet 2021
    Messages
    346
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Administrateur de base de données

    Informations forums :
    Inscription : Juillet 2021
    Messages : 346
    Par défaut
    J'ai copié collé ton code, il ne se passe rien .....

  8. #8
    Invité
    Invité(e)
    Par défaut


    Bon ben tant pis, je vais regardé du côté de PyQt5, ça va être un carnage !

  9. #9
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 778
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 778
    Par défaut
    Salut,

    Concernant:

    Visiblement l'utilisation de la fonction itemconfig(tagOrId, option) rafraichit l'affichage, je voudrais l'empêcher en quelque sorte.
    c'est normal: les itemconfig sont faits dans un autre thread que celui qui "affiche".

    Le thread qui attend dans .mainloop exécute le boulot à faire posté par l'autre thread. Python ne permettant pas l'exécution de ces threads en parallèle, ça prend des plombes (switcher les threads pour effectuer chaque opération) et au lieu d'être fait en une seule fois, c'est découpé.

    Avec un GUI, on est supposé utiliser des threads que dans des cas particuliers (puisqu'un GUI a son propre threading) et qui respectent "l'atomicité" implicite des modifications d'état du multitâche coopératif. A défaut, on a des soucis... qu'on ne va pas résoudre parce que c'est programmé en dépit du bon sens.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  10. #10
    Invité
    Invité(e)
    Par défaut
    Et voici la version PyQt5, sans connaissance préliminaire et ça marche impec' :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    import time, threading, random
    import win32gui, win32con, win32api
    import ctypes
    from PIL import Image
    from PIL.ImageQt import ImageQt
    import locale
     
    locale.setlocale(locale.LC_TIME,'')
     
    ####PARAMETRES####
    IdleTime = 1000  #msec
     
    ####VARIABLES####
    wallpaper = None
    wallpaper_path = None
    wallpaperized = False
    idle = False
    win_title = 'WALLPAPER.py-'+str(random.getrandbits(128)) #Nom de fenêtre Tkinter random
    DAY = None
    time_clic = 0
     
    def getIdleTime():
        return (win32api.GetTickCount() - win32api.GetLastInputInfo())
     
    #Met à jour le canvas (si changement de wallpaper)
    def getWallpaper():
        global wallpaper, wallpaper_path
        ubuf = ctypes.create_unicode_buffer(512)
        ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_GETDESKWALLPAPER,len(ubuf),ubuf,0)
        path = ubuf.value
     
        user32 = ctypes.windll.user32
        user32.SetProcessDPIAware()
        [WIDTH, HEIGHT] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
     
        if wallpaper_path != path:
            wallpaper_path = path
            wallpaper = Image.open(path)
            w, h = wallpaper.size
            ratio_w = w/WIDTH
            ratio_h = h/HEIGHT
            if ratio_w > ratio_h:
                W, H = (int(w/ratio_w), int(h/ratio_w))
                wallpaper = wallpaper.resize((W, H))
                black = Image.new('RGB', (WIDTH, HEIGHT), color = 'black')
                black.paste(wallpaper, (int((WIDTH-W)/2), int((HEIGHT-H)/2)))
                wallpaper = black.copy()
            elif ratio_w <= ratio_h:
                W, H = (int(w/ratio_h), int(h/ratio_h))
                wallpaper = wallpaper.resize((W, H))
                black = Image.new('RGB', (WIDTH, HEIGHT), color = 'black')
                black.paste(wallpaper, (int((WIDTH-W)/2), int((HEIGHT-H)/2)))
                wallpaper = black.copy()
     
            wallpaper = ImageQt(wallpaper)                          #Transforme le wallpaper en image QT
            try:
                win.change_wallpaper(wallpaper)
            except NameError:                                       #La fenêtre n'est pas encore créée
                pass
     
    #TITLE = []
    #Retourne False si une fenêtre est ouverte (sauf ce logiciel et qq programmes windows), une exception est alors soulevée par EnumWindows
    def winEnumHandler( hwnd, liste ):
        if win32gui.IsWindowVisible( hwnd ) and not win32gui.IsIconic(hwnd):
            title = win32gui.GetWindowText( hwnd )
            liste.append((hwnd, title))
            for word in ('','Expérience d’entrée Windows','Program Manager','Paramètres','Hôte contextuel',\
                         'Centre de notifications','Calculatrice','Alarmes et horloge','Drag','Pense-bêtes', 'Gestionnaire des tâches', win_title):
                if title == word:
                    break
     
            else:
                return False
     
    def boucle():
        global IdleTime, wallpaperized, idle, DAY
     
        time.sleep(0.1)
        getWallpaper()
        try:
            liste = []
            win32gui.EnumWindows( winEnumHandler, liste )
        except:                                                                 #Une fenêtre est ouverte (exceptée celles autorisées)
            wallpaperized = False
            idle = False
        else:                                                                   #Si aucune exception soulevée alors aucune fenêtre n'est ouverte, on est donc sur le bureau grosso-modo
            title = win32gui.GetWindowText(win32gui.GetForegroundWindow())
     
            if not title:                                                       #On est vraiment sur le bureau
                if not wallpaperized:                                           #On n'a pas déjà affiché le wallpaper (sécurité inutile ?)
                    if time.time()-time_clic > 0.5:
                        wallpaperized = True
                        win.show()                                                  #On affiche le wallpaper
     
            if not idle:
                if getIdleTime()>IdleTime :
                    idle = True
                    wallpaperized = True
                    win.show()                                                  #On affiche le wallpaper
     
        date = time.strftime('%A, %d %B, %Y %H:%M:%S').capitalize()
        date = date.split(' ')
        hour = date[-1]
        day = ' '.join((date[0:-1]))
        if day != DAY:
            DAY = day
            win.change_date(hour, day)
        else:
            win.change_date(hour, False)
     
        QTimer.singleShot(100, boucle)
     
     
     
    from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
    from PyQt5.QtGui import QPixmap, QFont, QPen
    from PyQt5.QtCore import Qt, QTimer
    import sys
     
    class Window(QMainWindow):
        def __init__(self, hour, day, wallpaper):
            super().__init__()
     
            #self.acceptDrops()
            # set the title
            self.setWindowTitle(win_title)
     
            # this will hide the title bar
            self.setWindowFlag(Qt.FramelessWindowHint)
     
            # setting  the geometry of window
            self.setGeometry(0, 0, 1920, 1080)
     
            # creating label
            self.label = QLabel(self)
     
            # loading image
            #self.pixmap = QPixmap(path)
            self.pixmap = QPixmap.fromImage(wallpaper)
     
            # adding image to label
            self.label.setPixmap(self.pixmap)
     
            # Optional, resize label to image size
            self.label.resize(self.pixmap.width(),
                              self.pixmap.height())
     
            # creating label1
            self.label1 = QLabel(self)
            self.label1.resize(1920, 1080)
            self.label1.setText(hour)
            self.label1.setFont(QFont('French Script MT', 200, QFont.PreferAntialias))
            self.label1.move(0, -50)
            self.label1.setAlignment(Qt.AlignCenter)
            self.label1.setStyleSheet("color : black; font-weight: bold")
     
            # creating label2
            self.label2 = QLabel(self)
            self.label2.resize(1920, 1080)
            self.label2.setText(hour)
            self.label2.setFont(QFont('French Script MT', 200, QFont.PreferAntialias))
            self.label2.move(0, -50)
            self.label2.setAlignment(Qt.AlignCenter)
            self.label2.setStyleSheet("color : white")
     
            # creating label3
            self.label3 = QLabel(self)
            self.label3.resize(1920, 1080)
            self.label3.setText(day)
            self.label3.setFont(QFont('French Script MT', 50, QFont.PreferAntialias))
            self.label3.move(-1, 90)
            self.label3.setAlignment(Qt.AlignCenter)
            self.label3.setStyleSheet("color : black")
     
            # creating label4
            self.label4 = QLabel(self)
            self.label4.resize(1920, 1080)
            self.label4.setText(day)
            self.label4.setFont(QFont('French Script MT', 50, QFont.PreferAntialias))
            self.label4.move(+1, 90)
            self.label4.setAlignment(Qt.AlignCenter)
            self.label4.setStyleSheet("color : black")
     
            # creating label5
            self.label5 = QLabel(self)
            self.label5.resize(1920, 1080)
            self.label5.setText(day)
            self.label5.setFont(QFont('French Script MT', 50, QFont.PreferAntialias))
            self.label5.move(0, 90)
            self.label5.setAlignment(Qt.AlignCenter)
            self.label5.setStyleSheet("color : white")
     
     
            # show all the widgets
            #self.show()
     
        def change_wallpaper(self, wallpaper):
            self.pixmap = QPixmap.fromImage(wallpaper)
            self.label.setPixmap(self.pixmap)
     
        def change_date(self, hour, day):
            self.label1.setText(hour)
            self.label2.setText(hour)
            if day:
                self.label3.setText(day)
                self.label4.setText(day)
                self.label5.setText(day)
     
        #Réafficher le bureau au clic
        def mousePressEvent(self, event):
            global idle, time_clic
            idle = False
            time_clic = time.time()
            self.hide()
     
    # create pyqt5 app
    app = QApplication.instance() 
    if not app:
        app = QApplication(sys.argv)
     
    getWallpaper()
     
    date = time.strftime('%A, %d %B, %Y %H:%M:%S').capitalize()
    date = date.split(' ')
    hour = date[-1]
    day = ' '.join((date[0:-1]))
     
    win = Window(hour, day, wallpaper)
     
    win.show()
    win.hide()
     
    QTimer.singleShot(200, boucle)
     
    app.exec_()
    Mise à jour : QTimer.singleShot(100, boucle) à la place du threading...
    Dernière modification par Invité ; 15/08/2022 à 22h16.

  11. #11
    Invité
    Invité(e)
    Par défaut
    Ouai à force de vouloir me passer de la fonction after(), j'en finis par oublier comment ça marche. after c'est pas vraiment du threading, si ?
    Bref, en tout cas ça marche impec ! Me reste plus qu'à utiliser QTimer.singleShot() comme after avec PyQt5 je suppose...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    import time, threading, random, os
    import win32gui, win32con, win32api
    import ctypes
    import tkinter as tk
    from PIL import ImageTk, Image
    import locale
     
    locale.setlocale(locale.LC_TIME,'')
     
    ####PARAMETRES####
    IdleTime = 1000  #msec
     
    ####VARIABLES####
    wallpaper = None
    wallpaper_path = None
    wallpaperized = False
    idle = False
    win_title = 'WALLPAPER.py-'+str(random.getrandbits(128)) #Nom de fenêtre Tkinter random
    chemin = os.path.expanduser('~\Wallpaper')
     
    def getIdleTime():
        return (win32api.GetTickCount() - win32api.GetLastInputInfo())
     
    # Afficher le bureau quand on clic gauche sur le wallpaper
    def on_click(event):
        global idle
        root.withdraw()
        idle = False
     
    #Met à jour le canvas (si changement de wallpaper)
    def getWallpaper():
        global wallpaper, wallpaper_path
        ubuf = ctypes.create_unicode_buffer(512)
        ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_GETDESKWALLPAPER,len(ubuf),ubuf,0)
        path = ubuf.value
     
        if wallpaper_path != path:
            wallpaper_path = path
            wallpaper = Image.open(path)
            w, h = wallpaper.size
            ratio_w = w/WIDTH
            ratio_h = h/HEIGHT
            if ratio_w > ratio_h:
                W, H = (int(w/ratio_w), int(h/ratio_w))
                wallpaper = wallpaper.resize((W, H))
                black = Image.new('RGB', (WIDTH, HEIGHT), color = 'black')
                black.paste(wallpaper, (int((WIDTH-W)/2), int((HEIGHT-H)/2)))
                wallpaper = black.copy()
            elif ratio_w <= ratio_h:
                W, H = (int(w/ratio_h), int(h/ratio_h))
                wallpaper = wallpaper.resize((W, H))
                black = Image.new('RGB', (WIDTH, HEIGHT), color = 'black')
                black.paste(wallpaper, (int((WIDTH-W)/2), int((HEIGHT-H)/2)))
                wallpaper = black.copy()
     
            #wallpaper = ImageOps.fit(wallpaper, (WIDTH,HEIGHT)) #Redimensionne l'image à la taille de l'écran  
            wallpaper = ImageTk.PhotoImage(wallpaper)           #Transforme l'image pour Tkinter
            canvas.itemconfig(container, image=wallpaper)       #Met à jour le canvas
     
    #Affiche la fenêtre tkinter
    def displayWallpaper():    
        root.deiconify()    
     
    #TITLE = []
    #Retourne False si une fenêtre est ouverte (sauf root et qq programmes windows), une exception est alors soulevée par EnumWindows
    def winEnumHandler( hwnd, liste ):
        if win32gui.IsWindowVisible( hwnd ) and not win32gui.IsIconic(hwnd):
            title = win32gui.GetWindowText( hwnd )
            liste.append((hwnd, title))
            for word in ('','Expérience d’entrée Windows','Program Manager','Paramètres','Hôte contextuel',\
                         'Centre de notifications','Calculatrice','Alarmes et horloge','Drag','Pense-bêtes', 'Gestionnaire des tâches', win_title):
                if title == word:
                    break
                    #return True
            else:
                return False
     
    #Fenêtre tkinter
    def mainroot():
        global wallpaperized, idle
     
        getWallpaper()
        try:
            liste = []
            win32gui.EnumWindows( winEnumHandler, liste )
        except:                                                                 #Une fenêtre est ouverte (exceptée celles autorisées)
            wallpaperized = False
            idle = False
        else:                                                                   #Si aucune exception soulevée alors aucune fenêtre n'est ouverte, on est donc sur le bureau grosso-modo
            title = win32gui.GetWindowText(win32gui.GetForegroundWindow())
     
            if not title:                                                       #On est vraiment sur le bureau
                if not wallpaperized:                                           #On n'a pas déjà affiché le wallpaper (sécurité inutile ?)
                    wallpaperized = True
                    threading.Thread(target=displayWallpaper, daemon=True).start()           #On affiche le wallpaper
     
            if not idle:
                if getIdleTime()>IdleTime :
                    idle = True
                    wallpaperized = True
                    threading.Thread(target=displayWallpaper, daemon=True).start()
     
     
        date = time.strftime('%A, %d %B, %Y %H:%M:%S').capitalize()
        date = date.split(' ')
        hour = date[-1]
        day = ' '.join((date[0:-1]))
     
        canvas.itemconfig(hour_b, text=hour)
        canvas.itemconfig(hour_f, text=hour)
        canvas.itemconfig(day_l, text=day)
        canvas.itemconfig(day_r, text=day)
        canvas.itemconfig(day_f, text=day)
     
        root.after(100, mainroot)
     
    root = tk.Tk()
    root.title(win_title)
     
    WIDTH, HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry(f'{WIDTH+4}x{HEIGHT+4}+-2+-2')    
    #root.attributes('-fullscreen',True )
    root.overrideredirect(1)                                                #Mettre la fenêtre par dessus tout
    #root.attributes('-topmost',True )
    canvas = tk.Canvas(root, width = WIDTH, height = HEIGHT)    
    container = canvas.create_image(2,2, anchor=tk.NW)                      #Garder le canvas en mémoire
     
    date = time.strftime('%A, %d %B, %Y %H:%M:%S').capitalize()
    date = date.split(' ')
    hour = date[-1]
    day = ' '.join((date[0:-1]))
     
    hour_b = canvas.create_text(int(WIDTH/2),int(HEIGHT/2)-50, font=('French Script MT', 200, 'bold'), fill='black', text = hour)
    hour_f = canvas.create_text(int(WIDTH/2),int(HEIGHT/2)-50, font=('French Script MT', 200), fill='white', text = hour)
    day_l =  canvas.create_text(int(WIDTH/2)-1,int(HEIGHT/2)+90, font=('French Script MT', 50), fill='black', text = day)
    day_r =  canvas.create_text(int(WIDTH/2)+1,int(HEIGHT/2)+90, font=('French Script MT', 50), fill='black', text = day)
    day_f =  canvas.create_text(int(WIDTH/2),int(HEIGHT/2)+90, font=('French Script MT', 50), fill='white', text = day)
     
    canvas.pack()
     
    root.withdraw()                                                         #Cacher la fenêtre
    root.bind("<ButtonRelease-1>", on_click)                                #"Binder" la fenêtre entière pour la cacher
     
    root.after(0, mainroot)
     
    root.mainloop()

  12. #12
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 778
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 778
    Par défaut
    Citation Envoyé par LeNarvalo Voir le message
    Et voici la version PyQt5, sans connaissance préliminaire et ça marche impec'
    Un truc qui marche par hasard(*), c'est juste prendre de mauvaises habitudes... Et des problèmes insolubles lorsque ça ne voudra plus marcher.

    (*) Avec Qt on utilise des QThreads et des signaux pour changer l'état d'un objet géré par un autre thread. Ca marche/ca marche pas devient sinon une question de "timing".

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  13. #13
    Invité
    Invité(e)
    Par défaut
    Okay !

    Je viens d'aller regarder ce site : https://realpython.com/python-pyqt-qthread/

    C'est sacrément complexe contrairement à un "simple" Threading qui semble fonctionner beaucoup plus rapidement avec PyQt5 qu'avec Tkinter.
    QTimer.singleShot() ne permet pas de faire du multithreading par hasard ?

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Convolution trop lente...
    Par progfou dans le forum Traitement d'images
    Réponses: 6
    Dernier message: 05/08/2006, 11h44
  2. [Eclipse] Editeur de code trop lent
    Par Benzeghiba dans le forum Eclipse Java
    Réponses: 6
    Dernier message: 10/11/2005, 14h02
  3. boucle while trop lente
    Par atouze dans le forum Access
    Réponses: 17
    Dernier message: 15/06/2005, 16h35
  4. [SAGE] ODBC trop lent
    Par tileffeleauzed dans le forum Décisions SGBD
    Réponses: 1
    Dernier message: 14/11/2004, 09h56
  5. Envoi de mail trop lent
    Par MASSAKA dans le forum ASP
    Réponses: 3
    Dernier message: 15/10/2004, 10h57

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo