huong
huong

Reputation: 4564

Display image using menu command in the same window with the menu

I'm planning on having quite a lot of methods for my program so I need to implement these in external files and add it to menu commands after importing the file. But since menu commands takes only names of the methods, I'm not sure whether it can work if my method takes parameters. Below is the code for displaying an image in a file named file.py:

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

def open(root):
    filename = askopenfilename(filetypes=[("all files","*"),("Bitmap Files","*.bmp; *.dib"),
                                        ("JPEG", "*.jpg; *.jpe; *.jpeg; *.jfif"),
                                        ("PNG", "*.png"), ("TIFF", "*.tiff; *.tif")])
    image = Image.open(filename)
    image1 = ImageTk.PhotoImage(open(filename))
    root.geometry("%dx%d+%d+%d" % (image.size[0], image.size[1], 0, 0))
    panel = Label(root, image = image1)
    panel.pack(side='top', fill='both', expand='yes')
    panel.image = image1

I also have a file named gui.py, where I call the method open above in a command. So I did this:

menu.add_command(label="Open", command=file.open)

My idea is to display the image in the same window as the menu, so I guess the method open need to take the parameter root so when it is called in the menu, the image will be opened in that window. I'm not sure if it's logic but here is the error that I got:

Exception in Tkinter callback Traceback (most recent call last):
File "D:\Python32\lib\tkinter_init_.py", line 1399, in call return self.func(*args) TypeError: open() takes exactly 1 argument (0 given)

I'm new to Python and my question is a little bit messy but I really need help. Thanks.

Regarding the comment about binding, even though I'm not sure how to fix it, but when I add the parameter to the open method called as menu command, it works except that the method is called instead of being assigned to the command. How can I call the name of the method only but still include the parameter? This is bizarre for me.

Upvotes: 1

Views: 1718

Answers (1)

Nick ODell
Nick ODell

Reputation: 25269

Thanks for the comment about binding, even though I'm not sure how to fix it, but when I add the parameter to the open method called as menu command, it works except that the method is called instead of being assigned to the command.

Instead of using

menu.add_command(label="Open", myfunc(myarg))

use

menu.add_command(label="Open", lambda: myfunc(myarg))

This adds the argument, but waits to run the function until add_command decides to call it.

More about lambda

Upvotes: 2

Related Questions