func for button_press_event does not work

my func to fetch the key pressed on the keyboard does not do anything. Code runs without error.
The code is copied from the https://matplotlib.org/3.1.1/Matplotlib.pdf.
Looks that the func “on_press(event)” is not called at all.

matplotlib 3.8.0 py311hecd8cb5_0
matplotlib-base 3.8.0 py311h41a4f6b_0
matplotlib-inline 0.1.6 py311hecd8cb5_0
python 3.11.9 h657bba9_0_cpython conda-forge
OSX 10.15

Code:

import sys
import matplotlib.pyplot as plt
import matplotlib

Taste = "a"
Vorgang = "a" + " :"


def on_press(event):
   print("you pressed: ", event.name, " Key: ", event.key, " location: ", event.xdata, event.ydata)
   Taste = event.key
   Vorgang = event.name + "on_press-test"

fig, ax = plt.subplots(1,1)
ax = plt.gca()
plt.ion()
fig.canvas.mpl_connect('button_press_event', on_press)

while True:
   plt.plot([1.6, 2.7])
   plt.show()
   plt.title("interactive test")
   plt.xlabel("index")
   ax.plot([3.1, 2.2])
   if plt.waitforbuttonpress(25):
      print("Test-if1: ", Taste, " Vorgang: ",Vorgang)
      break
   ax.plot([5.1, 7.2])
   plt.draw()
   if plt.waitforbuttonpress(25):
      print("Test-if2: ", Taste, " Vorgang: ",Vorgang)
      break
   print("Test: ", Taste, " : ", Vorgang)

plt.ioff()

What do I do wrong?
Thanx to all for reviewing.

Screenshot with results attached. The line 26 prints his stuff but line 10 inside the func is not called.

Shows code running
result from print command in line 26 - but no print result from line 10
Result from print command in line 26 - but no print result from line 10 (func “on_press”)

Fixed it:

Problem was that the “global” statement was missing, so the function used the variables as function internal not the global ones.
Code that works:

import sys
import matplotlib.pyplot as plt
import matplotlib

Taste = "a"
Vorgang = "a" + " :"

def on_press(event):
    global Taste, Vorgang
    print("you pressed: ", event.name, " Key: ", event.key, " location: ", event.xdata, event.ydata)
    Taste = event.key
    Vorgang = event.name + " on_press-test"
    print ("Taste: ", Taste, "Vorgang: ", Vorgang, "event.key Type: ",type(event.key), "Taste type: ", type(Taste))

fig, ax = plt.subplots(1,1)
fig.canvas.mpl_connect('key_press_event', on_press)
ax = plt.gca()
plt.plot([1.6, 2.7])
plt.title("interactive test")
plt.xlabel("index")
ax.plot([5.1, 7.2])
ax.plot([3.1, 2.2])

#Data = plt#.ion()
#print ("DataElements: ", Data, "Type: ", type(Data))
for x in ax.get_lines():
    print (x, " - ", "0.0: ", x.get_xydata()[0,0], "|- 0.1: ", x.get_xydata()[0,1], "|- 1.0: ", x.get_xydata()[1,0], "|- 1.1: ", x.get_xydata()[1,1],)
plt.ion()
plt.show()
while True:
    #plt.show()
    if plt.waitforbuttonpress(5):
        print("Test-if1: ", Taste, " Vorgang: ",Vorgang)
        if Taste == "Q" or Taste == "q":
            print ("Quit!")
            sys.exit()
        if Taste =="m":
            ax.plot([2.1, 6.2])
            plt.draw()

# to end app.
plt.ioff()
plt.show()