python tkinter刷新显示图片
时间: 2023-09-09 15:09:55 浏览: 369
你可以用Tkinter中的Canvas对象来显示图片,并且可以通过更新Canvas对象来刷新图片。以下是一个简单的示例代码:
```python
import tkinter as tk
from PIL import Image, ImageTk
class App:
def __init__(self, master):
self.master = master
master.title("Image Display")
# Load image
self.image = Image.open("image.jpg")
self.photo = ImageTk.PhotoImage(self.image)
# Create canvas and display image
self.canvas = tk.Canvas(master, width=self.image.width, height=self.image.height)
self.canvas.pack()
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
# Create button to refresh image
self.button = tk.Button(master, text="Refresh", command=self.refresh_image)
self.button.pack()
def refresh_image(self):
# Reload image
self.image = Image.open("image.jpg")
self.photo = ImageTk.PhotoImage(self.image)
# Update canvas with new image
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
root = tk.Tk()
app = App(root)
root.mainloop()
```
在这个示例中,我们首先使用PIL库加载一张图片,并将其转换为ImageTk.PhotoImage对象。然后,我们使用Canvas对象在窗口中显示图片。最后,我们创建一个按钮,当点击时刷新图片。在refresh_image方法中,我们重新加载图片并更新Canvas对象。
阅读全文