Tkinter managing my event loops alongside my mainloop

前端 未结 2 463
滥情空心
滥情空心 2020-12-03 16:17

I\'ve been slowly learning Tkinter and object-oriented programming but I\'ve programmed myself into a corner with this one. please forgive my lack of critical thinking on th

2条回答
  •  萌比男神i
    2020-12-03 17:16

    You already have an infinite loop running, so you shouldn't be trying to add another one. Instead, you can use the after method to cause a function to be repeatedly called every so often. In your case, you can replace this:

    def updateStock(self):
       while True:
            labelName = str(s) + "Label"
            stockPrice = get_quote(s)
            self.labelName = Label(self.myContainer1, text = s.upper() + ": " + str(stockPrice))
            self.labelName.pack()
            time.sleep(10)
    

    ... with this:

    def updateStock(self):
        labelName = str(s) + "Label"
        stockPrice = get_quote()
        self.labelName = Label(self.myContainer1, text = s.upper() + ": " + str(stockPrice))
        self.labelName.pack()
        self.after(10000, self.updateStock)
    

    This will get a quote, add a label, then arrange for itself to be called again in 10 seconds (10,000 ms).

    However, I doubt that you want to create a new label every 10 seconds, do you? Eventually the window will fill up with labels. Instead, you can create a label once, then update the label in each iteration. For example, create self.label once in the init, then in the loop you can do:

    self.labelName.configure(text=s.upper() + ": " + str(stockPrice))
    

提交回复
热议问题