簡體   English   中英

Python3在Tkinter中打開帶有對話框的圖像

[英]Python3 open image with dialog box in Tkinter

我正在上一本書的python3課程,並且沒有任何解釋我在嘗試使用對話框(文件資源管理器)打開圖像時遇到此錯誤的方式,以明確可以使用Image打開圖像。 open() 但是當我用文件 explore 打開它時,我得到了這個:

"C:\Users\Yoant\Documents\Python Program\Programs\Tkinter-Course\Open File dialog box\venv\Scripts\python.exe" "C:/Users/Yoant/Documents/Python Program/Programs/Tkinter-Course/Open File dialog box/main.py"
Traceback (most recent call last):
  File "C:\Users\Yoant\Documents\Python Program\Programs\Tkinter-Course\Open File dialog box\main.py", line 16, in <module>
    my_img = ImageTk.PhotoImage(Image.open(root.filename))
  File "C:\Users\Yoant\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py", line 2900, in open
    prefix = fp.read(16)
  File "C:\Users\Yoant\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 246: character maps to <undefined>
# this is my code below:

from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image

root = Tk()
root.title("File Dialog box")

# Return the name and location of the file.
root.filename = filedialog.askopenfile(initialdir="/Pictures", title="select a file", filetypes=(("png files", "*.jpg"),("all file", "*.*")))

# Display dir of file selected
my_lbl = Label(root, text=root.filename).pack()

# Display image
my_img = ImageTk.PhotoImage(Image.open(root.filename))
my_lbl2 = Label(image=my_img).pack()

mainloop()

您應該使用askopenfilename()而不是askopenfile()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM