Home > Back-end >  How to call a function inside a function to work on a Tkinter button comand?
How to call a function inside a function to work on a Tkinter button comand?

Time:07-11

I need help. I'm developing a GUI where I have a function inside a function that I need to call in a tkinter button in order to make that button working, but I don´t how I can call the function that I need (func1).

Brief Code:

def func():
    def func1():
    func1()
func()

generatePDF = Button(fourthWindow, text="Gerar Relatório PDF", command=func1)

CodePudding user response:

If func doesn't return anything, you can let func return func1 then implement func in the button

CodePudding user response:

The question:

"I need help. I'm developing a GUI where I have a function inside a function that I need to call in a tkinter button in order to make that button working, but I don´t know how I can call the function that I need (func1)."

Note, that the example code does not match the question.

def func():
    def func1():
        func1()  # This line is recursively calling func1. Expect an infinite loop.


func()  # This line is calling the outer function.
func1()  # This call would fail. func1 is not in scope.

generatePDF = Button(fourthWindow, text="Gerar Relatório PDF", command=func1)

What the question describes is perfectly valid and sometimes needed. The type of function is known as a closure.

# An example:

def func():
    # Contains some desired stable state, data structure etc.
    # For example a list data structure
    the_data = [x ** 2 for x in [0, 1, 2, 3, 4]]
    print(f'{the_data =}')

    def func1(index):
        """Process the stable data. Get the cube root"""
        cube_root = the_data[index] ** (1 / 3)
        return f'The {cube_root=} of {the_data[index]=}.'

    return func1  # return the inner function for use


call_back = func()  # returns func1.
# I named this callback because the user wants to use it in:
# generatePDF = Button(fourthWindow, text="Gerar Relatório PDF", command=call_back )
print(f'{type(call_back)=}')
print(call_back(3))

Output:

the_data =[0, 1, 4, 9, 16]
type(call_back)=<class 'function'>
The cube_root=2.080083823051904 of the_data[index]=9.
  • Related