简体   繁体   中英

root after doesn't call the callback function

I'm trying to implement a root.after in a function to give a little time to a sensor to read but I'm not able to make it work. Here is the function code that I can't make it work:

def read_wifi():
global graph_data
try:
    del graph_data
except:
    pass

graph_data=np.array([0])
flag = True
while graph_data.shape[0] < 64:
    while flag == True:
        texto='LX'
        connection.send(texto.encode())

        def callback_after():
            global graph_data
            print('a')              
            graph_data=connection.recv(1024).decode()
            connection.settimeout(3)
            graph_data=graph_data[:-2]
            graph_data=graph_data[0:]
            graph_data=graph_data[:].split()
            graph_data = np.nan_to_num(graph_data)
            try:
                graph_data = np.array([float(q) for q in graph_data])
                flag = False
            except:
                print('Error de lectura del sensor. Reintentando leer...')
            if graph_data.shape[0]<64:
                print('Error de lectura del sensor. Reintentando leer...')

        root.after(500,callback_after)                                  
try:
    graph_data = graph_data*m+b     
except:
    pass
graph_data = np.reshape(graph_data,[4,16])

As you can see, i've added a line to print 'a' just to check if the code enters the callback_after function but it never gets printed so I think that the problem is with the root.after(500,callback_after) line.

If I don't implement the callback function the root after seems to work but my tk window freezes every time it reads from the sensor. I also tried to put the read_wifi function in a new thread but it keeps freezing.

I hope I made it clear.

Best regards.

You never give the event loop a chance to process events, so they just keep stacking up.

As a general rule of thumb you should not have an infinite loop running inside a tkinter program since mainloop() already is an infinite loop.

A quick, ineffecient fix would be to call root.update_idletasks() inside your inner loop. A better solution would be to refactor your code so that you don't have an infinite loop ( while flag == True: ) inside another potentially infinite loop ( while graph_data.shape[0] < 64 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM