简体   繁体   中英

How to make button command to open image inside window in tkinter?

I am attempting to create a very simple image viewer in tkinter with two simple buttons view and close. I have the close button functioning as intended but I am unable to get my view button to open the specified image in my file directory. I have tried importing ImageTK to write a button command to open it but have so far been unsuccessful.

import tkinter as tk
from PIL import ImageTk,Image

class image_viewer:
    def __init__(self, win):  
        
        self.root = win
        
        
        self.root.title('ImageViewer')
        self.root.geometry('400x350')

        
        self.btnView = tk.Button(text='View', command= ImageTk.PhotoImage(Image.open(r"C:\Users\SteveSmith\eclipse-workspace\SteveSmith-ex1\src\raw\pythonIsFun.jpg")))
        self.btnView.pack(side=tk.LEFT)
        self.btnView.place(x=20, y=265)
        
        self.btnClose = tk.Button(text='close', command=self.root.destroy)
        self.btnClose.pack(side=tk.LEFT)
        self.btnClose.place(x=65, y=265)

def main():
    root = tk.Tk()
    image_viewer(root)
    root.mainloop()

if __name__ == '__main__':
    main()

There are a number of errors in your code and previously I closed it after picking one of them and marking it as a duplicate of another question that had been asked and answered before that covered that problem.

However, based on comments you made and after thinking it over, I decided to reopen it and attempt to address all or at least most of the issues I saw — otherwise it would likely have taken you quite a while to get everything fixed.

Here's the result:

from PIL import ImageTk, Image
import tkinter as tk

class ImageViewer:
    def __init__(self, root, image_filename):
        self.root = root
        self.image_filename = image_filename

        self.root.title('ImageViewer')
        self.root.geometry('400x350')

        self.canvas = tk.Canvas(self.root, width=300, height=300)
        self.canvas.place(x=10, y=10)

        self.btnView = tk.Button(text='View', command=self.view_image)
        self.btnView.place(x=20, y=265)

        self.btnClose = tk.Button(text='close', command=self.root.destroy)
        self.btnClose.place(x=65, y=265)

    def view_image(self):
        self.img = ImageTk.PhotoImage(Image.open(self.image_filename))  # Keep ref to image.
        self.canvas.create_image(20, 20, anchor=tk.NW, image=self.img)


def main(image_filename):
    root = tk.Tk()
    ImageViewer(root, image_filename)
    root.mainloop()

if __name__ == '__main__':
    main(r"C:\Users\SteveSmith\eclipse-workspace\SteveSmith-ex1\src\raw\pythonIsFun.jpg")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM