Minion Jim
Minion Jim

Reputation: 1279

Calling pack_forget () in a thread

I have a Python program that looks like this

from tkinter import *
import threading, time
def cancel ():
    print ("Stop!")
def thread ():
    threading.Thread (target = new).start ()
def new ():
    b.pack_forget ()
    c = Canvas (root, width = 200, height = 25, bg = "white")
    c.pack ()
    Button (root, text = "OK", command = root.destroy).pack ()
    try:
        for x in range (200):
            time.sleep (0.02)
            c.create_rectangle ((x, 2, x + 1, 26), outline = "green", fill = "green")
        root.destroy ()
    except: pass
root = Tk ()
root.title ("Threading")
b = Button (root, text = "Begin.", command = thread)
b.pack ()
root.mainloop ()

However, it crashes every time I call the pack_forget (). I know I can do it like this:

from tkinter import *
import threading, time
def cancel ():
    print ("Stop!")
def thread ():
    b.pack_forget ()
    threading.Thread (target = new).start ()
def new ():
    c = Canvas (root, width = 200, height = 25, bg = "white")
    c.pack ()
    Button (root, text = "OK", command = root.destroy).pack ()
    try:
        for x in range (200):
            time.sleep (0.02)
            c.create_rectangle ((x, 2, x + 1, 26), outline = "green", fill = "green")
        root.destroy ()
    except: pass
root = Tk ()
root.title ("Threading")
b = Button (root, text = "Begin.", command = thread)
b.pack ()
root.mainloop ()

For other programs, though, is it possible to call pack_forget in a thread. Thanks.

Upvotes: 1

Views: 248

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

You cannot call tkinter functions from a thread other than the thread where you created the GUI. You need to set up a thread-safe queue, and from the worker thread place something on the queue. The main thread can poll this queue and respond to the data.

For example, you could put something as simple as "pack_forget" on the queue, and when the main program pulls the string "pack_forget" off of the queue, it knows to call that function.

Upvotes: 4

Related Questions