Tktinter Menu with functionality in separate file

Viewed 16

It's my first time trying tkinter.

I'm trying to make a menu with the command section in another file. However it seems to run the command immediately as I open the program and doesn't wait till I click the menu button.

following is the code for my main:

import data
import loginPage
import menuFunc
from tkinter import *
import tkinter as tk

class main(Tk):
    def __init__(self):
        
        super().__init__()
        self.geometry("1000x700") #size of the window
        self.resizable(False,False) #dont let the user resize (might mess up layout of GUI)
        
    def Menu(self):
        myMenu = Menu(self)
        self.config(menu=myMenu)
        
        #Create a menu items
        optionMenu= Menu(myMenu)
        myMenu.add_cascade(label="Options", menu=optionMenu)
        optionMenu.add_command(label="Exit", command = self.destroy)
        
        addMenu= Menu(myMenu)
        myMenu.add_cascade(label="Add", menu=addMenu)
        addMenu.add_command(label="New Book", command = menuFunc.addBook(self))
        addMenu.add_command(label="New costumer", command = menuFunc.addCustomer(self))
        addMenu.add_command(label="New Employee", command = menuFunc.addEmployee(self))
        
            
    def Label(self):
         
         self.backGroundImage = PhotoImage(file = "Background.png") #photoimage for background
         self.backGroundImageLabel = Label(self, image = self.backGroundImage) #import the image as a label
         self.backGroundImageLabel.place(x=0, y=0) #placement
         
        # self.canvas = Canvas(self, width=550,height = 400) #show a canvas in front of background
         #self.canvas.place(x=75, y=70)

if __name__=="__main__":
    Main = main()
    Main.Label()
    Main.Menu()
    #Login.Entry()
    #Login.Button()
    Main.mainloop()

This is my code in the other file menuFunc.py

   from tkinter import *
import tkinter as tk

global addBookFrame
 
def addBook(window):
    addBookFrame = Frame(window, bg = "red")
    addBookFrame.pack(fill="both",expand = 1)
    
def addCustomer(window):
  
    addCustomerFrame = Frame(window, bg = "blue")
    addCustomerFrame.pack(fill="both",expand = 1)
        
def addEmployee(window):

    addEmployeeFrame = Frame(window, bg = "yellow")
    addEmployeeFrame.pack(fill="both",expand = 1)
    
def hideFrames(frame):
    for widget in frame.winfo_children():
        widget.destroy()

I get the following result:

enter image description here

How can I make it so that the function only runs when I press the appropriate menu button?

Thank you for your time.

1 Answers

Put:

command = menuFunc.addBook
command = menuFunc.addCustomer
command = menuFunc.addEmployee

In place of:

command = menuFunc.addBook(self)
command = menuFunc.addCustomer(self)
command = menuFunc.addEmployee(self)
Related