0

As a first project I decided to build an app that will show me the current price of oil so I will not have to look at the Forex charts whole time.

The issue with this app is that the "update" loop only prints oil price every 3 seconds, so I know that this loop is executed constantly, but it not only does not update the text in window, but it also crashes it, while shell prints the price of oil.

I tried to use Multiprocessing module but it made no difference.

def window():
    root = Tk()
    screen_width  = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    mylabel = Label( root, text = "" )
    mylabel.pack()

def update():
    while True:
        global string_price
        request = requests.get( "http://www.biznesradar.pl/notowania/BRENT-OIL-ROPA-BRENT#1d_lin_lin" )
        content = request.content
        soup = BeautifulSoup( content, "html.parser" )
        element = soup.find( "span", { "class": "q_ch_act" } )
        string_price = ( element.text.strip() )
        print( string_price )
        mylabel.configure( text = str( string_price ) )

        time.sleep( 3 )

root.after( 400, update )
mainloop()
user3666197
  • 1
  • 6
  • 50
  • 92

1 Answers1

2

.after method, already does what you wanted from while True and sleep at the same time. Remove both sleep and while and add another after inside to call continuously.

def custom_update():
    global string_price
    request = requests.get("http://www.biznesradar.pl/notowania/BRENT-OIL-ROPA-BRENT#1d_lin_lin")
    content = request.content
    soup = BeautifulSoup(content, "html.parser")
    element = soup.find("span", {"class": "q_ch_act"})
    string_price = (element.text.strip())
    print(string_price)
    mylabel.configure(text=str(string_price))
    root.after(3000, custom_update) #notice it calls itself after every 3 seconds

custom_update() #since you want to check right after opening no need to call after here as Bryan commented 
Community
  • 1
  • 1
Lafexlos
  • 7,618
  • 5
  • 38
  • 53
  • Thanks! It helped a lot! I also changed the time value in the "root.after" at the very bottom of your code for "0" so the app checks the oil price right after opening. – Karol Mularski Nov 14 '16 at 12:23
  • You don't need to use `after` the first time you call it. You can directly call `update()`. However, you should probably name the function something else. All widgets have an `update` method, so having your own `update` method might be confusing. – Bryan Oakley Nov 14 '16 at 12:30
  • @KarolMularski please check after edits as well. Some changes applied according to Bryan's suggestions. – Lafexlos Nov 14 '16 at 12:34
  • This piece of code works just great! I also deleted "global string_price", which was used when I was trying to run this app with multiprocessing module, now it is not needed. Thanks for help, you guys are the best! – Karol Mularski Nov 14 '16 at 18:48