0

I am working on a large program that opens new windows from a desktop widget. The desktop widget has a 'ticker' style label that displays a piece of text representing an iteration through a list. My problem is when I first wrote the program I called mainloop() with each new window I opened. The result was the new window and program would run as designed, but the ticker would freeze. Even upon closing the newly created window, the ticker would not restart. So I removed the mainloop() line. The result of this is the ticker continues to run and I can work within the new window, but everything is soooo laggy. I suspect this has something to do with the after() method?

Attached is a test code that I am using to try to sort this out before applying the correct code to my program. And I'm sure you can tell by reading the code, but I am self taught and an absolute newb, so please dumb down the explanations if possible. Thank so much!

from tkinter import *

def new_window():
    nw = Tk()
    item = Text(nw)
    item.grid()

L = [1, 2, 3, 4, 5]

root = Tk()
Button(root, text = 'Open', command = new_window).grid(row = 1)
while True:
    for i in L:
         num = Label(root, text = i)
         num.grid(row = 0)
         root.after(2500)
         num.update()

root.mainloop()
1
  • while True stops mainloop to do its job - handle events, redraw widgets, create new window, etc.. Besides you create thousands Labels which probably exists in memory and tkinter have to handle them even though you can not see them (because they are behind new Label). Commented Jan 18, 2016 at 0:30

1 Answer 1

1

A tkinter application should always have exactly one instance ofTk, and you should call mainloop exactly once. If you have more than one instance the program will not likely work the way you expect. It's possible to make it work, but unless you understand exactly what is happening under the hood you should stick to this rule of thumb.

If you need more windows, create instances of Toplevel. You should not call mainloop for each extra window.

Also, you shouldn't have an infinite loop where you call after the way that you do. mainloop is already an infinite loop, you don't need another. There are several examples on this website of using after to call a function at regular intervals without creating a separate loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.