I’m having a problem with Tkinter menu. Here is the code for my gui.py file:
from tkinter import *
from SS2 import file
class AppUI(Frame):
def __init__(self, master=None):
Frame.__init__(self, master, relief=SUNKEN, bd=2)
self.menubar = Menu(self)
menu = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label="File", menu=menu)
menu.add_command(label="Open", command=file.open())
menu.add_command(label="Save")
menu.add_command(label="Save as...")
menu.add_command(label="Exit",
command=root.quit)
menu = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label="Image", menu=menu)
menu.add_command(label="Size")
menu.add_command(label="Rotate")
menu.add_command(label="Crop")
menu = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label="Color", menu=menu)
menu = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label="Filter", menu=menu)
menu.add_command(label="Blur")
menu.add_command(label="Contour")
menu.add_command(label="Emboss")
menu.add_command(label="Smooth")
menu.add_command(label="Sharpen")
menu = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label="Help", menu=menu)
menu.add_command(label="About")
try:
self.master.config(menu=self.menubar)
except AttributeError:
# master is a toplevel window (Python 1.4/Tkinter 1.63)
self.master.tk.call(master, "config", "-menu", self.menubar)
self.canvas = Canvas(self, bg="white", width=400, height=400,
bd=0, highlightthickness=0)
self.canvas.pack()
root = Tk()
app = AppUI(root)
app.pack()
root.mainloop()
And here is the code for my file.py:
from tkinter import *
from tkinter.filedialog import askopenfilename
def open():
filename = askopenfilename(filetypes=[("allfiles","*"),("imagesfiles","*.png")])
The problem is, when I run the gui.py file, the file dialogue always appears before the menu, and when I close it and try to access it through the menu Open, nothing happens. What did I do wrong here? Please help and thanks in advance.
Commands should give the name of the method. What you’re doing is calling the method. Tkinter will then use the return value of that method as the button command. Solution: leave out the brackets.
instead of
You did it right for the exit button though!