Как показать изображения с пути в новом окне в Python TK - PullRequest
0 голосов
/ 17 ноября 2018

После просмотра пути к изображению я хочу показать изображение в следующем окне в python, используя библиотеку Tk, но изображение не отображается в следующем окне.Пожалуйста, посмотрите на мой код ниже и дайте ответ.

import tkinter as tk
from tkinter import filedialog as fd

a=""
str1 = "e"
class Browse(tk.Frame):
    """ Creates a frame that contains a button when clicked lets the user to select
    a file and put its filepath into an entry.
    """    
    def __init__(self, master, initialdir='', filetypes=()):
        super().__init__(master)
        self.filepath = tk.StringVar()
        self._initaldir = initialdir
        self._filetypes = filetypes
        self._create_widgets()
        self._display_widgets()

    def _create_widgets(self):
        self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10))
        a=self._entry
        self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse)
        self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify)
        self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14))

    def _display_widgets(self):

        self._label.pack(fill='y')
        self._entry.pack(fill='x', expand=True)
        self._button.pack(fill='y')
        self._classify.pack(fill='y')

    def retrieve_input(self):
        #str1 = self._entry.get()
        #a=a.replace('/','//')
        print (str1)

    def classify(self):
        newwin = tk.Toplevel(root)
        newwin.geometry("500x500")
        label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14))
        label.pack()
        canvas = tk.Canvas(newwin, height=300, width=300)
        canvas.pack()
        my_image = tk.PhotoImage(file=a, master=root)
        canvas.create_image(150, 150,  image=my_image)
        newwin.mainloop()

    def browse(self):
        """ Browses a .png file or all files and then puts it on the entry.
        """    
        self.filepath.set(fd.askopenfilename(initialdir=self._initaldir,
                                             filetypes=self._filetypes))


if __name__ == '__main__':
    root = tk.Tk()
    labelfont = ('times', 10, 'bold')
    root.geometry("500x500")
    filetypes = (
        ('Portable Network Graphics', '*.png'),
        ("All files", "*.*")
    )

    file_browser = Browse(root, initialdir=r"C:\Users",
                          filetypes=filetypes)
    file_browser.pack(fill='y')
    root.mainloop()    

1 Ответ

0 голосов
/ 17 ноября 2018

Ваша глобальная переменная a, в которой хранится путь к изображению, не обновляется. Вы должны явно сделать это. Ниже приведен код, который работает. Посмотрите на функцию browse().

import tkinter as tk
from tkinter import filedialog as fd

a=""
str1 = "e"
class Browse(tk.Frame):
    """ Creates a frame that contains a button when clicked lets the user to select
    a file and put its filepath into an entry.
    """
    def __init__(self, master, initialdir='', filetypes=()):
        super().__init__(master)
        self.filepath = tk.StringVar()
        self._initaldir = initialdir
        self._filetypes = filetypes
        self._create_widgets()
        self._display_widgets()

    def _create_widgets(self):
        self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10))
        a = self._entry
        self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse)
        self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify)
        self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14))

    def _display_widgets(self):
        self._label.pack(fill='y')
        self._entry.pack(fill='x', expand=True)
        self._button.pack(fill='y')
        self._classify.pack(fill='y')

    def retrieve_input(self):
        #str1 = self._entry.get()
        #a=a.replace('/','//')
        print (str1)
    def classify(self):
        global a
        newwin = tk.Toplevel(root)
        newwin.geometry("500x500")
        label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14))
        label.pack()
        canvas = tk.Canvas(newwin, height=300, width=300)
        canvas.pack()
        my_image = tk.PhotoImage(file=a, master=root)
        canvas.create_image(150, 150, image=my_image)
        newwin.mainloop()

    def browse(self):
        """ Browses a .png file or all files and then puts it on the entry.
        """
        global a
        a = fd.askopenfilename(initialdir=self._initaldir, filetypes=self._filetypes)
        self.filepath.set(a)

if __name__ == '__main__':
    root = tk.Tk()
    labelfont = ('times', 10, 'bold')
    root.geometry("500x500")
    filetypes = (
        ('Portable Network Graphics', '*.png'),
        ("All files", "*.*")
    )

    file_browser = Browse(root, initialdir=r"~/Desktop", filetypes=filetypes)
    file_browser.pack(fill='y')
    root.mainloop()

P.S. Измените initialdir . Я изменил это, поскольку я не на Windows.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...