tkinter doesn't open image via function

后端 未结 2 1465
孤城傲影
孤城傲影 2021-01-26 07:35

Tkinter doesn\'t open the image. We can ask the opening incorrectly, we need help. I need it to open the image through the menu. be sure to use pil, as the image can be anything

相关标签:
2条回答
  • 2021-01-26 08:13

    Here is what you have to do to solve the issue:

    def input_file():
        global photoimg #keeping a reference
        a = easygui.fileopenbox(filetypes=["*.jpg"])
        original = Image.open(a).resize((799, 799), Image.ANTIALIAS) #calling it all in one line
        photoimg = ImageTk.PhotoImage(original)
        canvas = Canvas(root, width=799, height=799)
        imagesprite = canvas.create_image(10, 10,anchor='nw', image=photoimg)
        canvas.pack()
        return imagesprite
    

    and then later remove the () around your function:

    file_menu.add_command(label = "Импорт...", command=input_file)
    

    What is being done?

    • In the first set of code im keeping a reference to the image so the image is not garbage collected by python. You can do so either by saying imagesprite.image = photoimg or global photoimg on top of the function. I also resized the image in the same line that I opened the image, to reduce codes.

    • And in the second set of codes, im just removing () so that the function is not called(invoked) before choosing the menu item.

    • And also tkinter itself has a filedialogbox that works like your easygui.fileopenbox(filetypes=["*.jpg"]), read some docs here

      from tkinter import filedialog
      
      a = filedialog.askopenfilename(title='Choose a file',initialdir='C:/',filetypes=(('All Files','*.*'),("JPEG 
      Files",'*.jpeg')))
      

    Hope this helped you solve the error, do let me know if any doubts.

    Cheers

    0 讨论(0)
  • 2021-01-26 08:25

    If I am not mistaken, your menu opens as soon as you run the application, not when you click the import button.

    It's because you need to pass the callback to the add_command, but you're calling the method instead

    file_menu.add_command(label = "Import...", command=input_file())
    

    Remove the () from input_file(). just pass input_file. it will not call the method directly anymore.

    file_menu.add_command(label = "Import...", command=input_file)
    
    0 讨论(0)
提交回复
热议问题