When execution a Tk-button's function and creating a label inside it, the gui does not update immediately

Viewed 59

i'm new in the python language and have been learning and working with it for 2 days now. I'm writing a code to send grbl files to my cnc-machine.

my code:

    def grbl_sturing(Gcode_file):

         print('running')
         lbl_Running = Label(root, text="running")
         lbl_Running.grid(row=0, column=2)

         #Grbl setup
         poort = serial.Serial('com11',115200)
         code = open(Gcode_file,'r');
         poort.write(b'\r\n\r\n')
         time.sleep(2)   
         poort.flushInput() 
 
         #sturing 
         for line in code:
              l = line.strip() 
              print ('Sending: ' + l)
              poort.write(l.encode() + b'\r\n') 
              grbl_out = poort.readline()
              print (' : ' + str(grbl_out.strip()))
 
         #Grbl afsluiten
         code.close()
         poort.close()

So when i press a button in my tkinter window i go to this fucntion. My intensions where to let me know in a label and in my cmd that the program is sending/running. But when i press this button my cmd show this:

running
Sending: $H
 : b'ALARM:9'

Don't mind the alarm its because the cnc-machine isn't powered.

In the cmd it works like itended but when i look in my tkinter window it runs first and when its done it shows me that it is running. Why does it do this and how can i fix it? thank you in advance.

ps(sorry for my bad English)

1 Answers

So, what is happening here is that you are creating the label, but the GUI isn't updating until later, to make it update in that order you must use the line:

 TK.update()

Where TK is your tkInter variable to force the interface to update at that point, instead of waiting for the main loop.

Related