How can I pass a function into a tkinter class if it’s in a separate .py file?

I am trying to use this “search_pressed()” function in my “main.py” file as a command passed into my Tk class in a separate file called “main_window.py”

But when I try to run the code, it says:

NameError: name 'tkinter_menu' is not defined

Here is the code from my main.py file:

from main_window import MainMenu

def search_pressed():
    tk_data = tkinter_menu.get_tk_entries()
    print(tk_data)

tkinter_menu = MainMenu(search_pressed)

And here is the code from my main_window.py file:

from tkinter import *

class MainMenu(Tk):
    def __init__(self, search_function):
        super().__init__()
        # Entry:
        self.entry = Entry(self)
        self.entry.grid(row=0, column=0, pady=2.5, columnspan=2)

        # Search Button
        self.search_button = Button(master=self, width=20, text="Search", bg="#53A1DB", command=search_function)
        self.search_button.grid(row=1, column=0, pady=5)

        self.mainloop()

    def get_tk_entries(self):
        tk_entry = self.entry.get()

        tk_data = {
            "tk entry": tk_entry,
        }
        return tk_data

Answer

The problem is that self.mainloop() never stops which means that the MainMenu(...) is still running. That is why the variable tkinter_menu is undefined.

To fix your problem:

  • remove self.mainloop() from main_window.py
  • change your main script to:
from main_window import MainMenu

def search_pressed():
    tk_data = tkinter_menu.get_tk_entries()
    print(tk_data)

tkinter_menu = MainMenu(search_pressed)
tkinter_menu.mainloop()