简体   繁体   English

我想打开一个文件对话框并将所选文件的位置作为参数传递给 tkinter 以在 gui 上显示?

[英]I want to open a file dialogue and pass the location of selected file as argument to tkinter to show on gui?

I am facing the problem that the filedialogue is returning _io.TextIOWrapper object while tkinter takes location of the file as string.我面临的问题是文件对话返回 _io.TextIOWrapper object 而 tkinter 将文件的位置作为字符串。

I tried every method to convert this _io.TextIOWrapper to string but failed.我尝试了各种方法将此 _io.TextIOWrapper 转换为字符串,但失败了。

Help me out!!帮帮我!!

import tkinter as tk
import tkinter.filedialog

from PIL import Image, ImageTk


class App(tk.Tk):
    def __init__(self):
      super().__init__()

      self.main = tk.Frame(self)
      self.main.grid(row=0, column=0)

      dial = tkinter.filedialog.askopenfile()

      self.disp_img = Image.open(dial).resize((400, 400))
      self.disp_img = ImageTk.PhotoImage(self.disp_img)

      self.img_label = tk.Label(self.main, image=self.disp_img)
      self.img_label.grid(row=0, column=0)


if __name__ == '__main__':
   app = App()
   app.withdraw()
   app.mainloop()

As said in a comment on the question, you want to use askopenfilename() instead of askopenfile() .正如对该问题的评论中所说,您想使用askopenfilename()而不是askopenfile() Alternatively, the TextIOWrapper object has a variable called name which contains the file name.或者, TextIOWrapper object 有一个名为name的变量,其中包含文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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