Skip to main content
 首页 » 编程设计

python之在 Python 中打开 JPEG 图像

2025年05月04日11txw1958

我在使用以下代码在 Python 2.7 中打开 jpeg 图像时遇到问题。

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()  

jpeg 可以正常打开,但随后代码停止运行。我想在程序中间打开 jpeg,但是一旦图像打开,其余代码都不会执行。

我还尝试使用下面的代码打开 jpeg,但只收到错误“No module named Image”。我已经安装了 PIL,它是正确的 2.7 版本。

import Image 
 
image = Image.open('File.jpg') 
image.show() 

如有任何帮助,我们将不胜感激。

请您参考如下方法:

Tkinter 是单线程的。 root.mainloop 调用进入负责显示和更新所有图形元素、处理用户事件等的 GUI 循环,阻塞直到图形应用程序退出。主循环退出后,您将无法再以图形方式更新任何内容。

因此,您可能需要重新考虑程序的设计。在主循环旁边运行您自己的代码有两种选择:

选项 1:在单独的线程中运行您的代码

在进入主循环之前,生成一个将运行您自己的代码的线程。

... 
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() 

选项 2:使用 Tk.after 在主循环中运行您的代码

root.after_idle(my_code) #will run my_code as soon as it can 
root.mainloop() 

警告 mainloop 负责所有与使 GUI 可用相关的事情。当您的代码在主循环线程中运行时(使用 root.after_idle 或 root.after 安排),GUI 将完全无响应(卡住),因此请确保您没有使用长时间运行的操作加载主循环。与选项 1 一样,在单独的线程中运行它们。

基本上,主线程必须运行主循环,并且您的代码只能使用上述方法并发运行,因此不幸的是您可能不得不重构整个程序。