我正在编写一个图像处理程序,需要在单击Tkinter按钮后获取图像作为用户输入。
这是我的代码:
root = tk.Tk()
#root.withdraw()
def file():
file = askopenfile(mode ='r', filetypes =[('JPG File', '*.jpg'),('PNG File','*.png')], encoding="utf8")
if file is not None:
content = file.read()
print(content)
open = tk.Button(root, text ="Open Image",command= lambda : file())
open.pack()
root.mainloop()
错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/Admin/.PyCharmCE2019.1/config/scratches/scratch_3.py", line 18, in <lambda>
open = tk.Button(root, text ="Open Image",command= lambda : file())
File "C:/Users/Admin/.PyCharmCE2019.1/config/scratches/scratch_3.py", line 12, in file
file = askopenfile(mode ='r', filetypes =[('JPG File', '*.jpg'),('PNG File','*.png')], encoding="utf8")
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\tkinter\filedialog.py", line 396, in askopenfile
filename = Open(**options).show()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\tkinter\commondialog.py", line 43, in show
s = w.tk.call(self.command, *w._options(self.options))
_tkinter.TclError: bad option "-encoding": must be -defaultextension, -filetypes, -initialdir, -initialfile, -multiple, -parent, -title, or -typevariable
答案 0 :(得分:0)
这是因为您将错误的模式传递给askopenfile
。您正在传递mode='r'
,但是应该传递mode='rb'
,因为图片是字节,还需要删除encoding
参数。