简体   繁体   English

如何通过单击 Python 中的 Tkinter 按钮接受图像作为用户输入?

[英]How to accept image as user input by clicking on Tkinter button in Python?

I am writing a program on image processing that needs to get an image as user input after clicking on a Tkinter button.我正在编写一个图像处理程序,需要在单击 Tkinter 按钮后获取图像作为用户输入。

Here's my code:这是我的代码:

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()

Error:错误:

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

This is because you are passing the wrong mode to askopenfile .这是因为您将错误的模式传递给askopenfile You are passing mode='r' but it should be mode='rb' since pictures are bytes also you need to remove the encoding argument.您正在传递mode='r'但它应该是mode='rb'因为图片也是字节,您还需要删除encoding参数。

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

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