2

I work on Python 3.10.2 and I just start to work with tkinter and I always have a problem with .after() method. For example with this program :

import tkinter as tk

def initialisation(compteur) :
    compteur=compteur+1
    print(compteur)
    root.after(2000,initialisation, compteur)

root=tk.Tk()    
initialisation(0)
root.mainloop()

I have this error :

1

invalid command name "1720125185344initialisation"
    while executing
"1720125185344initialisation"
    ("after" script)
2
3

It works but I still have this error 1 time. I have looked for solutions but I don't understand. Thank you in advance for your help.

EMT2
  • 23
  • 2
  • 1
    Hello! Seems like the peice of code you wrote works completely fine on my machine. Is this all your code or only a part of it? It seems like it is just a small part of it. Please provide more code as the error seems does not make any sense seeing only this part of code. – InfoDaneMent Feb 26 '22 at 10:54
  • Hello, it's all my code. I wrote it to try to solve the problem. Does this mean that it is my machine that has a problem? Thanks for your answer. – EMT2 Feb 26 '22 at 11:04
  • do you run your script inside an IDE or from terminal ? if in IDE try resetting kernel and see if you still get error – pippo1980 Feb 26 '22 at 11:28
  • @EMT2 Try debugging your code in your ide if you are using one, or use pdb, the built in python console debugger. You will be able to find some tutorials or documentation about pdb. – InfoDaneMent Feb 27 '22 at 07:48

1 Answers1

0

try adding del root at the end of the script:

import tkinter as tk

def initialisation(compteur) :
    compteur=compteur+1
    print(compteur)
    root.after(2000,initialisation, compteur)

root=tk.Tk()    
initialisation(0)
root.mainloop()

del root

pippo1980
  • 2,181
  • 3
  • 14
  • 30
  • Can you explain why this solution works? Isn't the garbage collector going to call `del root` anyways? – TheLizzard Sep 30 '22 at 20:12
  • Dont remember was 7 months ago, I believe was wondering if something was wrong with IDE kernel – pippo1980 Sep 30 '22 at 20:32
  • Right now I have a similar issue but I am running the program from the terminal. I have 8 after loops with >100 widgets so debugging has been a struggle. – TheLizzard Sep 30 '22 at 20:34
  • https://stackoverflow.com/questions/26168967/invalid-command-name-while-executing-after-script – pippo1980 Sep 30 '22 at 20:43
  • Figured it out, there are actually 16 after loops, and I wasn't calling `.after_cancel` on the other 8 after loops. Why doesn't `tkinter` do this automatically :'( – TheLizzard Sep 30 '22 at 20:46
  • not following but think is explained here : https://stackoverflow.com/questions/25702094/tkinter-after-cancel-in-python – pippo1980 Sep 30 '22 at 22:44