Reputation: 53
I am running into a problem opening jpeg images in Python 2.7 using the following code.
import Tkinter as tk
from PIL import ImageTk, Image
path = 'C:/Python27/chart.jpg'
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
The jpeg opens just fine but then the code stops running. I want to open the jpeg in the middle of the program but once the image opens none of the remaining code gets executed.
I also tried opening the jpeg using the code below but just get the error "No module named Image". I have installed PIL and it was the correct 2.7 version.
import Image
image = Image.open('File.jpg')
image.show()
Any help would be appreciated.
Upvotes: 2
Views: 11759
Reputation: 7292
Tkinter is single threaded. The root.mainloop
call enters the GUI loop responsible for displaying and updating all graphical elements, handling user events, and so on, blocking until the graphical application exits. After the mainloop has exited, you are no longer able to update anything graphically.
Therefore, you likely need to rethink the design of your program. You have two options for running your own code alongside the mainloop:
Option 1: Run your code in a separate thread
Before entering the main loop, spawn a thread that will run your own code.
...
def my_code(message):
time.sleep(5)
print "My code is running"
print message
my_code_thread = threading.Thread(target= my_code, args=("From another thread!"))
my_code_thread.start()
root.mainloop()
Option 2: Run your code within the mainloop with Tk.after
root.after_idle(my_code) #will run my_code as soon as it can
root.mainloop()
Warning The mainloop is responsible for everything related to making the GUI usable. While your code is running within the mainloop thread (scheduled with root.after_idle or root.after), the GUI will be completely unresponsive (frozen), so make sure you aren't loading the mainloop with long-running operations. Run those in a separate thread as in Option 1.
Basically, the main thread must run the main loop, and your code can run concurrently only using the methods outlined above, so you unfortunately probably have to restructure your entire program.
Upvotes: 1